如何在Rails 3.2中翻译ActiveRecord属性名称?

我的模型(用户)中有以下validation:

validates :first_name,:length => {:minimum => 2,:maximum => 50},:format => { :with => /[a-zA-Z]+/ } 

我的yml语言环境文件中有以下内容:

  attributes: first_name: too_short: "First name is too short" too_long: "First name is too long" invalid: "First name is not valid" 

现在,如果我启动rails console ,并编写以下内容:

 a = User.new a.valid? a.errors.full_messages 

我会看到以下错误:

 ["First name First name is too short", "First name First name is not valid"] 

如您所见,属性名称也预先添加到字段错误中。 到目前为止,在我的代码中,我已经使用了model.errors[:field] ,这将始终显示我在yml文件中的字符串,但我想将字符串更改为:

  attributes: first_name: too_short: " is too short" too_long: " is too long" invalid: " is not valid" 

并使用full_messages版本。 问题是,我不知道如何翻译属性名称。 比方说,我想先取名字,而不是名字。 我该怎么办?

你可以在这里找到答案http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models

在你的config / locale /(your_lang).yml中

 en: activerecord: models: user: Dude attributes: user: first_name: "Name first" 

使用您需要使用的语言符号更改“en:”

干杯

在Rails 5中,在attributes之后,我必须使用下划线中的模型名称命名。 像这样:

 pt-BR: activerecord: attributes: my_model_name_in_underscore: attribute_name: 'String' 

资料来源: https : //stackoverflow.com/a/5526812/1290457