Rails has_many, build, inverse_of

I have 2 models like:

class User < ActiveRecord::Base
    has_many :user_services, :inverse_of => :user

    validates_length_of :user_services, :maximum => 3
end

class UserService < ActiveRecord::Base
    belongs_to :user, :inverse_of => :user_services

    validates_associated :user
end

I would like to do something like:

user_service = user.user_services.build(...)
if user_service.save
...

but it throws the error "too high stack level". I guess due to validates_associated in combination with inverse_of. Does anyone know why this happened?

The save call directly to the user object and not to the user_service object seems to work, but I'm wondering if there is a way to do this in the reverse order.

Thank!

+5
source share
1 answer

This is because your checks are circularly dependent.

validates_length_of :user_services
validates_associated :user

http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#method-i-validates_associated

UPDATE

, :

class User < ActiveRecord::Base
  has_many :user_services, :inverse_of => :user
  validates_length_of :user_services, :maximum => 3
end

class UserService < ActiveRecord::Base
  belongs_to :user, :inverse_of => :user_services

  def user_services_amount
     return 0 if self.user.nil?
     self.user.user_services.length
  end

  validates :user_services_amount, :inclusion => { :in => 0..3 }
end
+3

All Articles