在 Rails 中路由静态控制器的最佳方法是什么?
我有一个 static_controller ,它负责站点中的所有静态页面,并在 paths.rb 中按如下方式工作:
map.connect ':id', :controller => 'static', :action => 'show'
我有一个静态页面,其中包含有关该信息的信息,并有一个联系表单。 我目前有一个contacts_controller,负责将联系人信息插入数据库。 在我的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 %>
依次提交给我的contacts_controller 的创建操作。 我的创建操作如下所示:
def create
@contact = Contact.new(params[:contact])
if @contact.save
flash[:notice] = "Email delivered successfully."
end
redirect_to "about"
end
问题是,当我重定向回“关于”页面时,表单的 error_messages 会丢失(因为表单的 error_messages 仅存在于一个请求,并且该请求在重定向时结束)。 我将如何保留 error_messages 并仍然将用户链接回 about 静态 url? 会话/闪存是否足够(如果是这样,我将使用什么代码来传递错误消息)或者我是否将整个事情搞错了?
谢谢!
I have a static_controller that is in charge of all the static pages in the site and works as follows in routes.rb:
map.connect ':id', :controller => 'static', :action => 'show'
I have a static page called about that among other information, has a contact form.
I currently have a contacts_controller that is in charge of inserting the contact information to the database.
Inside my routes.rb file, I have:
map.resources :contacts
My contact form (simplified) looks like this:
<% 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 %>
Which in turn submits to the create action of my contacts_controller.
My create action looks like this:
def create
@contact = Contact.new(params[:contact])
if @contact.save
flash[:notice] = "Email delivered successfully."
end
redirect_to "about"
end
The problem is, is the that when I redirect back to my about page the error_messages for the form get lost (since the error_messages for the form only exist for one request, and that request ends upon redirect).
How would I go about preserving the error_messages and still linking the users back to the about static url?
Would a session/flash be sufficient (if so, what code would I use to pass error messages) or am I going about this whole thing wrong?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为可能发生的情况是您需要渲染而不是重定向。
重定向终止请求,并告诉客户端向不同的地址发出新请求。这将丢失你的错误。
如果您的保存尝试失败,您希望通过再次呈现操作并显示错误来完成请求。
I think what might be going on is you need to render rather than redirect.
Redirect terminates the request, and tells the client to make a new request to a different address. That will lose your errors.
If your save attempt fails your want to complete the request by rendering the action again with the errors shown.