开发者

Rails has_many, build, inverse_of

I have 2 models like such:

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, :in开发者_如何学Pythonverse_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 a "stack level too deep" error. I assume because of the validates_associated combined with the inverse_of. Does anyone know why this happens?

Calling save directly on the user object rather than the user_service object seems to work but I am wondering if there is a way to achieve these in reverse.

Thanks!


This happens because your validates have circular dependency.

validates_length_of :user_services
validates_associated :user

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

UPDATE

You can remove circular dependency if you rewrite your code this way:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜