Can anyone explain why this happens?
mybox:$ ruby script/console
Loading development environment (Rails 2.3.5)
>> foo = Foo.new
=> #<Foo id: nil, customer_id: nil, created_at: nil, updated_at: nil>
>> bar = Bar.new
=> #<Bar id: nil, bundle_id: nil, alias: nil, real: nil, active: true, list_type: 0, body_record_active: false, created_at: nil, updated_at: nil>
>> bar.save
=> false
>> bar.errors.each_full { |msg| puts msg }
Real can't be blank
Real You must supply a valid email
=> ["Real can't be blank", "Real You must supply a valid email"]
So far that is perfect, that is what i want the error message to read. Now for more:
>> foo.bars << bar
=> [#<Bar id: nil, bundle_id: nil, alias: nil, real: nil, active: true, list_type: 0, body_record_active: false, created_at: nil, updated_at: nil>]
>> foo.save
=> false
>> foo.errors.to_xml
=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<errors>\n <error>Bars is invalid</error>\n</errors>\n"
That is what I can’t figure out. Why am I getting Bars is invalid versus the error messages displayed above, [“Real can’t be blank”, “Real you must supply a valid email”] etc.
My controller simply has a respond_to method with the following in it:
format.xml { render :xml => @foo.errors, :status => :unprocessable_entity }
How do I have this output the real error messages so the user has some insight into what they did wrong? How do I write my render method in my controller to show all of the appropriate error messages?
It’s because the errors for
barare stored in thebarobject. To get these errors you have to do something like this:It’s all convoluted to me, but I haven’t figured out the best way to get all the errors in one list (besides handling it my self). I understand the reasoning behind it (as each object should only know about it’s own errors). What I usually do is extent
ActiveRecord::Errorsand create a neweach_full_with_associationsfunction that returns them all.It all makes sense when you see it on a form with nested fields. In that case the errors are shown properly and all is good.