如何翻译活动记录模型validation

当我提交一个包含错误的表单时,它会返回一条错误消息。 如何使用i18n翻译这些错误消息? 我已经在我的视图中翻译了所有其他文本,所以我知道l18n在Rails中是如何工作的。 我现在得到这个:

2 errors prohibited this user from being saved: Email translation missing: nl.activerecord.errors.models.user.attributes.email.blank Email translation missing: nl.activerecord.errors.models.user.attributes.email.blank 

我想翻译标题和错误。

标题的翻译是:

 nl: activerecord: errors: template: header: one: "1 error prohibited this %{model} from being saved" other: "%{count} errors prohibited this %{model} from being saved" body: "There were problems with the following fields:" 

为了翻译错误消息,Rails将使用以下翻译顺序:

 activerecord.errors.models.user.attributes.name.blank activerecord.errors.models.user.blank activerecord.errors.messages.blank errors.attributes.name.blank errors.messages.blank 

所以你可以添加:

 nl: activerecord: errors: models: user: attributes: email: blank: "foo blank in nl bar baz" 

它在Rails国际化(I18n)API指南中有记录 ,可能会为您提供更多见解。

只需使用您可以在此处找到的荷兰语翻译文件。 它包含大多数(如果不是全部)ActiveRecordvalidation消息的翻译。

将文件复制到项目中的config/locales/

替代方法

如果您希望从更新的翻译中受益,请将以下内容添加到Gemfile而不是手动复制翻译文件:

 gem 'rails-i18n' 

导轨I18n指南很好地涵盖了这一点。

您可以在config/locales/nl.yml添加以下config/locales/nl.yml来转换属性:

 nl: activerecord: models: user: "User" attributes: email: "Email" 

对于错误消息,ActiveRecord将在以下命名空间中查找它们:

 activerecord.errors.models.[model_name].attributes.[attribute_name] activerecord.errors.models.[model_name] activerecord.errors.messages errors.attributes.[attribute_name] errors.messages 

modelattributevalue在您的翻译中进行插值和提供,例如:

 nl: errors: messages: blank: "Please fill the %{model}'s %{attribute}"