[英]How to validate existence of parent id in child model in Rails for nested attributes
[英]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.