0

我有一个 static_controller 负责站点中的所有静态页面,并在 routes.rb 中按如下方式工作:

map.connect ':id', :controller => 'static', :action => 'show'

我有一个关于该信息的静态页面,还有一个联系表格。我目前有一个联系人控制器,负责将联系人信息插入数据库。在我的 routes.rb 文件中,我有:

map.resources :contacts

我的联系表格(简化)如下所示:

<% form_for @contact do |f| %>
    <p class="errors"><%= f.error_messages %></p>  

    <p>
        <%= f.label :first_name %>
        <%= f.text_field :first_name %>
    </p>


    <p class="buttons"><%= f.submit %></p>
<% end %>

这又提交给我的联系人控制器的创建操作。我的创建操作如下所示:

def create
    @contact = Contact.new(params[:contact])
    if @contact.save
      flash[:notice] = "Email delivered successfully."
    end
    redirect_to "about"
end

问题是,当我重定向回我的 about 页面时,表单的 error_messages 会丢失(因为表单的 error_messages 仅针对一个请求存在,并且该请求在重定向时结束)。我将如何保留 error_messages 并仍然将用户链接回 about static url?会话/闪存是否足够(如果是,我将使用什么代码来传递错误消息)还是我将整个事情搞错了?

谢谢!

4

1 回答 1

2

我认为可能发生的是您需要渲染而不是重定向。重定向终止请求,并告诉客户端向不同的地址发出新请求。那将失去你的错误。如果您的保存尝试失败,您希望通过再次呈现操作并显示错误来完成请求。

def create
@contact = Contact.new(params[:contact])
if @contact.save
  flash[:notice] = "Email delivered successfully."
  redirect_to @contact #make a new request for the address of the new record or some other address if you want
else
  render :action => "new" #complete the request by rendering the new action with the @contact variable that was just created (including the @errors).
end
于 2010-04-04T00:43:26.737 回答