Rails 3 - Error Validation on nested resource
I'm really struggling with how to handle Error Handling in Rails 3. I have hacked some ideas that could work but would rather do it the proper way. If anyone can help or give guidance I would appreciate it. Here is what I have so far
ItemController
def show
@item = Item.find(params[:id])
@note = @item.notes.new
respond_with(@item)
end
NoteController
def create
@note = @item.notes.build(params[:note])
flash[:notice] = 'Your 开发者_高级运维note was successfully added!' if @note.save
respond_with(@item)
end
items/show.html.erb
<%= form_for ([@item, @note]), :html => {:id => 'form-add-item-note'} do |f| %>
I have tried
<%=f.error_messages%>
<%=error_messages_for :note%>
<%=error_messages_for :item,:note%>
and even have a template for handling errors
<%= render "global/error_messages", :target => @item %>
which contains
<% if target.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(target.errors.count, "error") %> prohibited this record from being saved:</h2>
<ul>
<% target.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
I believe I'm losing the errors to the redirect but I can't seem to quite get how to redirect or render the item controller from the failed save in the note create and I would love to be able to pass the error global template the @note and it render the errors
If you redirect, you'll lose any error messages. You need to render a view, instead of redirecting if your object isn't valid and does not save. I'm not sure yet of the best way to do it in rails3 with the respond_with method, but if you look at the scaffolding rails3 generates, you see how handling failed saves works.
respond_to do |format|
if @post.save
format.html { redirect_to(@post, :notice => 'Post was successfully created.') }
format.xml { render :xml => @post, :status => :created, :location => @post }
else
format.html { render :action => "new" }
format.xml { render :xml => @post.errors, :status => :unprocessable_entity }
end
end
精彩评论