我有一个嵌套属性,我在其上执行状态验证。我没有成功地尝试为完整错误消息文本中返回的属性名称提供翻译。
该模型名为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和其他地方阅读了其他问题但没有成功。为属性名称编写翻译的正确方法是什么?
答案 0 :(得分:11)
向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
按顺序尝试路径,匹配的第一个是将要使用的路径。
答案 1 :(得分:-1)
试试这个:
en:
activerecord:
errors:
models:
identity:
attributes:
identity:
blank: 'Your new error message here'
答案 2 :(得分:-1)
您只需在db属性名称前面提供已翻译的值。
en:
activerecord:
attributes:
identity: # this is model name
identity: "translated attribute name"
您可能想要阅读有关活动模型attribute localization
的更多信息