2011-03-09 279 views
0

可以說襯衫上有錯誤。錯誤還會出現在person.errors中嗎? 如果是這樣,我怎麼能達到它? (我不希望使用person.shirt.errors)軌道上的紅寶石has_many驗證

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

你正在運行代碼,你可以簡單地嘗試一下,看看 – Jimmy 2011-03-09 16:41:01

+0

其實我沒有運行代碼,我試圖瞭解Ruby的錯誤mechanisem爲了實現它的一些地方 – batz107 2011-03-09 16:42:14

回答

0

根據這篇文章似乎對兒童實體錯誤將會在被複制到父保存,看到here -> Validations section雖然這可能是因爲改變

Validations simply work as you'd expect; 
#valid? will also validate nested models, 
#save(false) will save without validations, etc. 

The only thing to note is that all error messages 
from the nested models are copied to the parent errors 
object for error_messages_for. This will probably change 
in the future, as discussed on the ticket, but that's 
outside of the scope of this patch. 
+0

thx爲參考 – batz107 2011-03-10 09:00:58

0

它應該加載到「person.errors」中。你可以通過調用

person.errors.at(:<replace_this_with_name_of_attribute>) 

達到它,你也可以撥打

person.errors.each { |attr, msg| puts "attr = '#{attr}', msg = '#{msg}'" } 

檢查所有的錯誤屬性的名稱和相應的錯誤信息。祝你好運!

+0

襯衫是一個has_many協會。所以,如果錯誤在襯衫[2]中,我會通過寫入person.errors.at(:shirt [2])來達到這個錯誤。 – batz107 2011-03-10 09:02:50

+0

如果錯誤在襯衫[2] .color內,錯誤將出現在person.errors.at(:shirt [2] .color)或person.errors.at(:shirt [2])中,或者可能會出現這兩種情況? thx – batz107 2011-03-10 09:04:16

+0

有人對我最後的評論有一個答案嗎? – batz107 2011-03-10 13:59:17