ruby on rails has_many验证

时间:2011-03-09 16:33:11

标签: ruby-on-rails ruby validation

让我们说衬衫有错误。错误会出现在person.errors中吗? 如果是这样,我怎么能达到它? (我不想使用person.shirt.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?

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分:0)

它应加载到“person.errors”中。您可以致电

与其联系
person.errors.at(:<replace_this_with_name_of_attribute>)

您也可以致电

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

检查所有错误属性名称和相应的错误消息。祝你好运!