Catching an error for a child resource in Ruby on Rails
What is the best way to add errors to render if a child resource is really what's having issues and not the parent resource? In english what I mean is the following.. imagine the following code:
@foo =开发者_Python百科 Foo.new
foochild = Foochild.new
// break foochild somehow
@foo << foochild
@foo.save
now when I do:
format.xml { render :xml => @foo.errors }
All I get is a notice that foochild is invalid. It doesn't contain the message it should have that's contained in my validates_format_of method. How do I get it to show that message instead of the generic foochild is invalid? Is there something I have to do for that message to bubble up to its parent resource to show up in @foo.errors?
Always use "validates_associated" for this type of developmen. For example in your controller
@foo = Foo.new
@foochild = @foo.foo_childs.build
if @foo.save
else
format.xml { render :xml => @foo.errors }
end
and in your view
<%= error_messages_for :foo, :foo_child %>
精彩评论