Ruby-on-rails rails3 上的注意事项和错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4529136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:58:45  来源:igfitidea点击:

notices and errors on rails3

ruby-on-railsruby-on-rails-3

提问by denniss

I read somewhere that rails 3 form helper does not have error messages embedded in it anymore. I am wondering how I am supposed to show flash messages when I set them up inside my controller or as an inline notice in redirect_to? How am I supposed to display them on my view? Is there helper for this?

我在某处读到 rails 3 表单助手不再嵌入错误消息。我想知道在我的控制器中设置 Flash 消息或作为 redirect_to 中的内联通知时,我应该如何显示它们?我应该如何在我的视图中显示它们?有这方面的帮手吗?

For example if I have

例如,如果我有

def update
  if @person.save
    flash[:notice] = "Successfully saved!"
  end
end

how do i show the notice on my view?

如何在我的视图中显示通知?

回答by Brian Deterling

flash will still work as long as you display it in your layouts:

只要您在布局中显示 flash,它仍然可以工作:

<div id="page">
  <% if flash[:alert] %>
    <p class="flash-error"><%= flash[:alert] %></p>
  <% end %>
  <% if flash[:notice] %>
    <p class="flash-notice"><%= flash[:notice] %></p>
  <% end %>
  <%= yield %>
</div>

You can either display error messages manually or use the dynamic_formgem which gives you the old behavior.

您可以手动显示错误消息,也可以使用dynamic_formgem 为您提供旧行为。

回答by Joshua Partogi

You can still display flash messages in your view with this:

您仍然可以通过以下方式在视图中显示 Flash 消息:

<%= flash[:notice] %>

But if you want to display for error messages:

但是如果你想显示错误信息:

  #In your form
  <%= form_for @foo do |f| %>
    <%= render "shared/error_messages", :target => @foo %>
    ...
  <% end %> 


#shared/_error_messages.html.erb
<% if target.errors.any? %>
<div id="error_explanation">
  <ul>
  <% target.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <% end %>
  </ul>
</div>
<% end %>