Rails里面改变validate错误信息默认的属性名字

例如有如下代码

1
2
3
class User < ActiveRecord::Base
  validates :name, :presence => true
end

默认的错误信息将会为

1
Name can't be blank

如果想改变错误信息为 “User Name can’t be blank”怎么实现呢?

1
2
3
4
5
6
7
8
9
10
11
12
class User < ActiveRecord::Base
  validates :name, :presence => true

  HUMANIZED_ATTRIBUTES = {
    :name => "User Name"
  }

  def self.human_attribute_name(attr, options={})
    HUMANIZED_ATTRIBUTES[attr.to_sym] || super
  end

end