开发者

Change error field name in Rails

I'm wondering if there's a way to change the field name for a validation error it's associated with. For 开发者_开发百科example, if I submit First Name (really fname in the table) without any data, it yells Fname can't be blank.

Is it possible to change this to First Name can't be blank?


The general practice now-a-days is to edit your locals like so:

# config/locales/en.yml
en:
  activerecord:
    attributes:
      user:
        fname: "First Name"

Your error message will now say "First Name can't be..."

For completeness sake, you have another option. Which is to add the following to your User Model:

class User < ActiveRecord::Base

  HUMANIZED_ATTRIBUTES = {
    :fname => "First Name"
  }

  def self.human_attribute_name(attr, options = {}) # 'options' wasn't available in Rails 3, and prior versions.
    HUMANIZED_ATTRIBUTES[attr.to_sym] || super
  end

end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜