`
rshua
  • 浏览: 23142 次
  • 性别: Icon_minigender_1
  • 来自: jx
文章分类
社区版块
存档分类
最新评论

rails3 error_messages_for replacement

阅读更多

在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 %>
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics