繁体   English   中英

嵌套表单-如何基于子模型的输入来验证父模型?

[英]nested form - how to validate parent model based on inputs on child model?

有一个嵌套的形式,关系就像这样

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

class InspectionComponent < ActiveRecord::Base
  belongs_to :inspection

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

谢谢!

编辑:为了使事情更清楚一些,这是我尝试做的一个例子。

检查具有属性状态。 InspectionComponent也具有属性状态。

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

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

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

希望这很清楚,谢谢。

好的,如果我发布的另一个答案对其他人有用的话,请提供一个新答案。 专门针对您的问题,我认为您需要以下内容:

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

您要使用validates_associated

大概是这样的:

validates_associated :inspection_components

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM