验证祖父母:两个父母有同一个父母?

时间:2012-06-28 16:27:47

标签: ruby-on-rails validation model-associations

所以我正在编写一个包含以下模型和关联的应用程序:

class Company < ActiveRecord::Base
  has_many :customers, :dependent => :destroy
  has_many :goals, :dependent => :destroy
end

class Customer < ActiveRecord::Base
  belongs_to :company
  has_many :tasks
  has_many :goals, through: :tasks
end

class Goal < ActiveRecord::Base
  has_many :tasks, :dependent => :destroy
  belongs_to :company
  has_many :customers, through: :tasks
end

class Task < ActiveRecord::Base
  belongs_to :goal
  belongs_to :customer
end

现在在视图中,form_for新任务已经选择了目标或客户,而另一个关联选择是基于其他模型的过滤集。从理论上讲,用户不可能在两个不同的公司下创建任务,即@ task.goal.company == @ task.customer.company。

但是通过验证检查只有一个祖父母来看似乎是一种好习惯。我理解使用Proc.new你可以验证是否符合某个标准,但我希望它始终有效,所以这不是我正在寻找的解决方案。

感谢。

BTW让我知道模型结构是否显得嘲笑,或者我是否已根据rails惯例做了明确的事情。

1 个答案:

答案 0 :(得分:0)

proc.new和方法在验证方面完全相同。那就是说,你可能正在寻找这样的东西:

class Task < ActiveRecord::Base
  belongs_to :goal
  belongs_to :customer

  validate :companies_match

  private

  def companies_match
    self.errors.add(:base, "Goal company and customer company must be equivalent") unless goal.company == customer.company
  end
end