Rails has_many,build,inverse_of

时间:2011-04-19 03:48:54

标签: ruby-on-rails ruby-on-rails-3 activerecord associations has-many

我有2个这样的模型:

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

我想做点什么:

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

但它会引发“堆栈级太深”的错误。我假设因为validates_associated与inverse_of结合。有谁知道为什么会这样?

直接在用户对象上调用save而不是user_service对象似乎有效,但我想知道是否有办法反向实现这些。

谢谢!

1 个答案:

答案 0 :(得分:3)

这是因为您的验证具有循环依赖性。

validates_length_of :user_services
validates_associated :user

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

<强>更新

如果以这种方式重写代码,则可以删除循环依赖:

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