嵌套形式 - 如何根据子模型的输入验证父模型?
有一个嵌套表单,关系就像这样,
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 编辑表单具有嵌套的 InspectionComponents,并且可以更新此表单上的每个模型的状态。仅当所有 @inspection_component.status == 'complete' 时,@inspection.status 才应被标记为 'complete'。
因此,在验证@inspection时,我必须能够看到用户为@inspection_component.status输入的内容。
显然,我可以访问控制器中两个实例的参数,但是在应该进行验证的模型中,我没有看到实现这种情况的方法。
希望这是清楚的,谢谢。
Have a nested form, the relationship is like so
class Inspection < ActiveRecord::Base
has_many :inspection_components
accepts_nested_attributes_for :inspection_components
class InspectionComponent < ActiveRecord::Base
belongs_to :inspection
I have a custom validate method in Inspection which depends on attributes entered for InspectionComponent. How can I validate - InspectionComponent attributes are not saved or available in validation for Inspection.
Thanks!
EDIT: To make things a bit more clear, here's an example of what I'm trying to do.
Inspection has an attribute status.
InspectionComponent also has an attribute status.
The Inspection edit form has nested InspectionComponents and one can update each model's status' on this form. @inspection.status should only be able to be marked 'complete' if all @inspection_component.status == 'complete'.
Therefore, when validating @inspection, I must be able to see what the user entered for @inspection_component.status.
Obviously I have access to the params of both instances in the controller however in the model, where validation should occur, I don't see a way of making this happen.
Hopefully that is clear, thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,一个新的答案,以防我发布的另一个答案对其他人有用。针对您的问题,我认为您需要这样的东西:
Ok, a new answer in case the other one I posted is useful to someone else. Specifically for your issue, I think you need something like this:
您想要使用
validates_linked
。可能是这样的:
对其进行搜索并查找 api。此方法还有一些有用的选项。
You want to use
validates_associated
.probably something like:
Do a search on it and look up the api. There are some useful options for this method as well.