Rails 3.0弃用了f.error_messages
,现在需要一个插件才能正常工作——不过我想学习如何以(新的)原生方式显示错误消息.我遵循的是getting started guide,它在实现注释表单时使用了不推荐的方法.例如:
<h2>Add a comment:</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
<%= f.error_messages %>
<div class="field">
<% f.label :commenter %><br />
<%= f.text_field :commenter %>
</div>
<div class="field">
<%= f.label :body %><br />
<%= f.text_area :body %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
以下是正确的方法(由脚手架生成):
<%= form_for(@post) do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
. . .
我知道我在后一个例子中使用了@post
变量,但在前一个例子中,我应该引用哪个变量来获取用于创建注释的错误消息?