---
title: "rails3 error_messages_for replacement"
author: "rshua"
date: "2011-02-18T13:03:25Z"
tags: ["HTML"]
categories: ["编程语言"]
slug: "rails3-error-messages-for-replacement"
draft: false
lastmod: "2011-02-18T13:03:25Z"
id: 909965
url: "https://rshua.iteye.com/blog/909965"
---

在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 %>
```