[英]How to translate active record model validations
当我提交一个包含错误的表单时,它会返回一条错误消息。 如何使用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指南中有记录 ,可能会为您提供更多见解。
只需使用您可以在此处找到的荷兰语翻译文件。 它包含大多数(如果不是全部)ActiveRecord验证消息的翻译。
将文件复制到项目中的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
model
, attribute
和value
在您的翻译中进行插值和提供,例如:
nl:
errors:
messages:
blank: "Please fill the %{model}'s %{attribute}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.