0

我真的在为如何处理 Rails 3 中的错误处理而苦苦挣扎。我已经破解了一些可行的想法,但宁愿以正确的方式去做。如果有人可以提供帮助或提供指导,我将不胜感激。这是我到目前为止所拥有的

项目控制器

def show
    @item = Item.find(params[:id])
    @note = @item.notes.new
    respond_with(@item)
  end

笔记控制器

def create
    @note = @item.notes.build(params[:note])
    flash[:notice] = 'Your note was successfully added!' if @note.save
    respond_with(@item)
  end

项目/show.html.erb

<%= form_for ([@item, @note]),  :html => {:id => 'form-add-item-note'} do |f| %>

我努力了

<%=f.error_messages%> 
<%=error_messages_for :note%>
<%=error_messages_for :item,:note%> 

甚至有一个处理错误的模板

    <%= render "global/error_messages", :target => @item %>

其中包含

<% 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 %>

我相信我丢失了重定向的错误,但我似乎无法完全了解如何从注释创建中的失败保存中重定向或呈现项目控制器,我希望能够将错误全局模板传递给@note 并呈现错误

4

1 回答 1

1

如果您重定向,您将丢失任何错误消息。如果您的对象无效且未保存,您需要渲染视图,而不是重定向。我还不确定在 rails3 中使用 respond_with 方法的最佳方法,但是如果您查看 rails3 生成的脚手架,您会看到处理失败的保存是如何工作的。

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
于 2010-10-24T18:30:36.357 回答