在rails3中取消了error_messages_fo方法。新增了ActiveModel::Errors方法。
具有error_messages_for功能的方法:
在application_helper.rb增加方法:
def errors_for(object, message=nil)
html = ""
if object && object.errors.present?
html << "<div class='formErrors #{object.class.name.humanize.downcase}Errors'>\n"
if message.blank?
if object.new_record?
html << "\t\t<h5>There was a problem creating the #{object.class.name.humanize.downcase}</h5>\n"
else
html << "\t\t<h5>There was a problem updating the #{object.class.name.humanize.downcase}</h5>\n"
end
else
html << "<h5>#{message}</h5>"
end
html << "\t\t<ul>\n"
object.errors.full_messages.each do |error|
html << "\t\t\t<li>#{error}</li>\n"
end
html << "\t\t</ul>\n"
html << "\t</div>\n"
end
html
end
然后在页面中调用:
<%= (errors_for(@user)).html_safe %>
另外还有一种比较简单的使用方法:
<% if @user.present? && @user.errors.any? %>
<ul>
<% @user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>