我有一个嵌套属性,我在其上执行状态验证。我正在尝试没有成功提供完整错误消息文本中返回的属性名称的翻译。
该模型被称为 Identity
并包含一个名为的属性 identity
该模型嵌套在另一个模型中 has_many
关系。
当前返回典型的错误消息,如下所示
Identities identity can't be blank
我想翻译属性(默认情况下) Identities identity
进入别的东西。
我有
en:
activerecord:
models:
identity:
identity: "whatever"
如果我这样做,我会收到错误
I18n::InvalidPluralizationData (translation data {:identity=>"whatever"} can not be used with :count => 1):
我试图通过改变上面的内容来为此添加复数数据
en:
activerecord:
models:
identity:
identity:
one: "one"
other: "other"
这会将错误更改为
I18n::InvalidPluralizationData (translation data {:identity=>{:one=>"one", :other=>"other"}} can not be used with :count => 1):
我也试过了 many
代替 other
没有区别。
我已经花了几个小时试图完成这项工作,在Stack Overflow和其他地方阅读了其他问题但没有成功。为属性名称编写翻译的正确方法是什么?
添加一些调试输出到 human_attribute_name
方法揭示了i18n路径应该是什么。
这个例子有一个 user
模型与 has_many :identities
关系。所需的属性是 identity
,属性 Identity
模型,其中 User
模型 有很多。
我看了看 gems/activemodel-4.0.1/lib/active_model
,文件 translation.rb
。该 human_attribute_name
方法查找以下路径:
:"activerecord.attributes.user/identities.identity"
它还指定以下内容 默认,这是后备翻译:
:"activerecord.attributes.user/identities.identity"
:"activerecord.attributes.identities.identity"
:"attributes.identity"
"Identities identity"
"Identity"
最后两个是字符串,如果没有表示为符号的路径匹配可用的翻译,则第一个匹配。因此,在没有翻译的情况下,输出将是字符串“Identities identity”(另一个字符串,“Identity”将永远不会被使用)。
因此,以下任何转换路径都可以使用:
activerecord.attributes.user/identities.identity
activerecord.attributes.identities.identity
attributes.identity
路径按此顺序尝试,第一个匹配的是将要使用的路径。
尝试这个:
en:
activerecord:
errors:
models:
identity:
attributes:
identity:
blank: 'Your new error message here'
您可以在db属性名称前面提供已翻译的值。
en:
activerecord:
attributes:
identity: # this is model name
identity: "translated attribute name"
您可能想要阅读有关活动模型的更多信息 属性本地化