has_many:通过子验证和父验证

时间:2011-07-26 02:06:46

标签: ruby ruby-on-rails-3

我有一个rails 3.0 has_many:X,:through => :设置的东西,我有一个自定义验证器,在一些复杂的逻辑上做一些自定义验证。我想当你在这个多对多的关系中添加任何东西时,两个模型都有效吗?

项目类:

class Project < ActiveRecord::Base
  has_many :assignments
  has_many :users, :through => :assignments

  validates :name, :presence => true
end

分配:

class Assignment < ActiveRecord::Base
  belongs_to :project
  belongs_to :user
end

具有自定义验证程序的用户类:

class MyCustomValidator < ActiveModel::Validator
  def validate( record )
    if record.projects.length > 3
      record.errors[:over_worked] = "you have to many projects!"
    end
  end
end

class User < ActiveRecord::Base
  has_many :assignments
  has_many :projects, :through => :assignments

  validates :name, :presence => true
  validates_with MyCustomValidator
end

我真正想要做的是防止每个模型使另一个模型失效 防止

my_user.projects << fourth_project

my_project.users << user_with_four_projects_already

发生了。现在它允许分配,只有用户变得无效。

1 个答案:

答案 0 :(得分:1)

class Project < ActiveRecord::Base
  has_many :assignments
  has_many :users, :through => :assignments

  validates :name, :presence => true
  validates_associated :users
end

根据文档,必须已将用户分配给项目才能进行验证。所以:

my_user.projects << fourth_project

会发生,然后项目将验证用户并确认它确实无效,使项目无效以及反向示例。