---
title: "Re: [问题]关于验证后出错的显示"
author: "cvu"
date: "2007-05-09T00:26:16Z"
tags: ["ActiveRecord", "Rails", "Ruby"]
slug: "re"
draft: false
lastmod: "2007-05-09T00:26:16Z"
id: 78066
url: "https://cvu.iteye.com/blog/78066"
---

seairy在论坛里问：

> 在models添加validates_xxx方法后，页面的出错信息标题如何更改默认呢？
> 
> 比如红色框的标题是
> 1 error prohibited this customer from being saved
> 
> 还有就是我更改了environment.rb中的ActiveRecord::Errors.default_error_messages，例如：:blank => "不能为空"，但是错误提示中显示的字段名仍然是英文，例如：“Name 不能为空”，请问“Name”如何更改为我希望的名称呢？


我的解决方案是，在app/helpers/application_helper.rb里重写rails的error_messages_for函数：

```ruby

  def error_messages_for(object_name, options = {})
    options = options.symbolize_keys
    object = instance_variable_get("@#{object_name}")
    if object && !object.errors.empty?
      content_tag("div",
        content_tag(
          options[:header_tag] || "h2",
          "保存该#{object.class::ALIAS}时发生#{object.errors.count}个错误。"
        ) +
        content_tag("ul", object.errors.collect { |attr, msg| content_tag("li", object.class::COLUMN_ALIASES[attr] + msg) }),
        "id" => options[:id] || "errorExplanation", "class" => options[:class] || "errorExplanation"
      )
    else
      ""
    end
  end

```


请注意这里面的两个ALIAS，一个是object.class::ALIAS，一个是object.class::COLUMN_ALIASES。就用你的例子来说明这两个alias：

```ruby

class Customer < ActiveRecord::Base
  ALIAS = '客户'
  COLUMN_ALIASES = {
    'name' => '客户名称',
    'address' => '地址'
    # some other columns
  }
  
  # other codes in this model
end

```


这样的话，再加上你在environment.rb中设置的ActiveRecord::Errors.default_error_messages，他的报错信息就会是：
<span style="color:red">保存该客户时发生2个错误。
    * 客户名称不能为空。
    * 地址不能为空。</span>

今天看到一个很好的i18n/l10n的Ruby库：[gibberish](http://require.errtheblog.com/plugins/browser/gibberish/README)。这是一个很干净，很ruby的实现方式，也许用它可以有更好的解决方法。