0

有嵌套形式,关系是这样的

class Inspection < ActiveRecord::Base
  has_many :inspection_components
  accepts_nested_attributes_for :inspection_components

class InspectionComponent < ActiveRecord::Base
  belongs_to :inspection

我在 Inspection 中有一个自定义验证方法,它取决于为 InspectionComponent 输入的属性。如何验证 - InspectionComponent 属性未保存或在检查验证中可用。

谢谢!

编辑:为了让事情更清楚一点,这是我正在尝试做的一个例子。

检查具有属性状态。InspectionComponent 也有一个属性 status。

检查编辑表单具有嵌套的检查组件,可以在此表单上更新每个模型的状态。如果所有@inspection_component.status == '完成',@inspection.status 应该只能被标记为'完成'。

因此,在验证@inspection 时,我必须能够看到用户为@inspection_component.status 输入的内容。

显然,我可以访问控制器中两个实例的参数,但是在应该进行验证的模型中,我看不到实现这一点的方法。

希望这很清楚,谢谢。

4

2 回答 2

1

好的,一个新的答案,以防我发布的另一个答案对其他人有用。特别针对您的问题,我认为您需要这样的东西:

class Inspection < ActiveRecord::Base
  has_many :inspection_components
  accepts_nested_attributes_for :inspection_components

  # we only care about validating the components being complete
  # if this inspection is complete. Otherwise we don't care.
  validate :all_components_complete, :if => :complete

  def complete
    self.status == 'complete'
  end

  def all_components_complete
    self.inspection_components.each do |component|
      # as soon as you find an incomplete component, this inspection
      # is INVALID!
      Errors.add("field","msg") if component.status != 'complete'
    end
  end
end

class InspectionComponent < ActiveRecord::Base
  belongs_to :inspection
end
于 2010-09-10T04:45:03.947 回答
0

你想用validates_associated.

可能是这样的:

validates_associated :inspection_components

对其进行搜索并查找api。此方法也有一些有用的选项。

于 2010-09-10T00:30:57.683 回答