2011-03-03 112 views
0

如何執行驗證檢查(和插入錯誤消息到一個錯誤結構),其上是HAS_ONE關聯的屬性。Ruby on Rails的 - 的has_many屬性驗證

如果「襯衫」或「褲子」發生錯誤,我如何訪問該錯誤? 公司將在person.shirt.errors錯誤[:顏色]?

當我觸發person.save,針對person.shirt驗證激活?

當我觸發person.save併發生person.shirt錯誤時,錯誤消息將保存在哪裏?在person.shirt.errors或person.errors?

class Person < ActiveRecord::Base 
     has_one : shirt 
     has_many : pants 
     validates :name, :presence => true 
     validates_length_of :name, :minimum => 3 
end 

person = Person.new(:name => "JD") 
person.shirt.create(:color=> "red") 
person.pants.create(:type=> "jeans") 
person.valid? 
+0

由於某種原因,我不能夠添加註釋到以前的答案,所以我寫我的意見在這裏。 edgarjs(或任何其他人),關於這種方式的最後一個問題。 如果錯誤在褲子[2] .color內,錯誤將出現在'person.errors.at(:shirt [2] .color)'或'person.errors.at(:shirt [2])中'或者可能兩種情況? 如何獲取has_many關聯對象的錯誤消息? thx – batz107 2011-03-13 14:09:57

回答

2

,當你調用person.save您可以驗證模型的關聯與

validates_associated :shirt 

這樣,它會觸發shirt的驗證。

是的,您可以通過person.shirt.errors訪問關聯的錯誤,但請確保在觸發驗證後執行此操作。例如:

person = Person.new 
person.errors # => will be empty 

這是因爲驗證尚未運行。所以,你需要調用savevalid?或觸發驗證任何其他方法。

person = Person.new 
person.valid? 
person.errors # => will have errors in person 

而且它的協會一樣的:

person.shirt.valid? 
person.shirt.errors 

但因爲你是用validates_associated驗證的關聯也就足夠用person.valid?引發襯衫的驗證。

+0

edgarjs thx爲迴應。如果錯誤在襯衫中,它是否也會出現在person.errors中? – batz 2011-03-03 15:59:42

+0

edgarjs,你有沒有改變看我的評論? – batz 2011-03-06 08:50:29

+0

對不起,剛剛閱讀您的評論。如果錯誤是在襯衫,它將作爲「襯衫是無效的」,但沒有更多的細節,但你可以隨時訪問'person.shirt.errors'得到襯衫的錯誤出現在人。 – edgarjs 2011-03-07 23:01:54