2010-09-10 50 views
0

有一個嵌套的形式中,該關係是像這樣嵌套窗體 - 如何基於子模型上的輸入驗證父模型?

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

class InspectionComponent < ActiveRecord::Base 
    belongs_to :inspection 

我在檢查一個自定義的驗證方法,其取決於爲InspectionComponent輸入的屬性。我如何驗證 - InspectionComponent屬性在檢驗驗證中未保存或可用。

謝謝!

編輯:爲了讓事情更清楚些,下面是我想要做的一個例子。

檢查具有屬性狀態。 InspectionComponent也有一個屬性狀態。

檢查編輯表單嵌套了InspectionComponents,並且可以更新此表單上的每個模型的狀態。如果@ inspection_component.status =='complete',@ inspection.status應該只能標記爲'complete'。

因此,在驗證@inspection時,我必須能夠看到用戶爲@ inspection_component.status輸入的內容。

很明顯,我可以訪問控制器中兩個實例的參數,但是在應該進行驗證的模型中,我沒有看到實現這種情況的方法。

希望這很清楚,謝謝。

+0

我的回答有幫助嗎? – DJTripleThreat 2010-09-11 07:54:46

+0

這是的,但它沒有解決整個問題,請在下面的帖子下面看到我的評論。謝謝。 – 46and2 2010-09-12 06:41:55

回答

0

您想使用validates_associated

大概是這樣的:

validates_associated :inspection_components 

做就可以搜索和查找的API。這種方法也有一些有用的選項。

+0

嗨 - 感謝您的回覆。這裏的問題是,這仍然是互相獨立進行驗證。我的意思是,在Inspection驗證中,您不知道InspectionComponent子項中發生了什麼變化,反之亦然,在InspectionComponent驗證中,您不確定已向Inspection父級提交了什麼內容。 – 46and2 2010-09-10 00:57:10

+0

嗯...我可能需要看到更多的代碼才能更好地理解你想要做什麼。你可以編輯你的文章或給我更多關於你想要做的事情的信息嗎?通常,我會從'rails my_app'向''這樣的文件發佈逐步的指令:',這給我一個很好的答案。 – DJTripleThreat 2010-09-10 01:27:24

+0

嗨DJTripleThreat - 我已經更新了OP,希望能夠更清楚我想要做什麼,感謝您的期待。 – 46and2 2010-09-10 01:44:51

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 
+0

嗨DJTT,再次,謝謝。有趣的是,這種類型的驗證策略確實可以用於創建檢查並且它是InspectionComponents,但是一旦情況是更新,我似乎無法訪問驗證方法中的子項InspectionComponents * updated *屬性(all_components_complete )。當我調試並檢查每個inspection_component時,它們仍然具有舊的值。 – 46and2 2010-09-12 05:22:09

+0

好吧,讓我再想一想,看看我能想出什麼。 **編輯:**我得到這個爲我工作。如果您發佈了您的電子郵件地址,我會通過電子郵件向您發送我建立的項目。我想你可能在你的觀點上做錯了什麼,或者在你嘗試更新它們之前用屬性做某件事。 – DJTripleThreat 2010-09-13 07:59:20