开发者

ruby on rails has_many validations

Lets say there is an error in shirt. will the error appear also in person.errors ? and if so, how can i reach it ? ( i don't want to use 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")开发者_Go百科
person.valid?


According to this post it seems errors on child entities will be copied to the parent during a save, see here -> Validations section although this might have been changed since

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.


It should load into "person.errors". You can reach it by calling

person.errors.at(:<replace_this_with_name_of_attribute>)

You can also call

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

to check for all the error attribute names and the corresponding error messages. Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜