问题 翻译模型嵌套属性验证消息


我有一个嵌套属性,我在其上执行状态验证。我正在尝试没有成功提供完整错误消息文本中返回的属性名称的翻译。

该模型被称为 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和其他地方阅读了其他问题但没有成功。为属性名称编写翻译的正确方法是什么?


8288
2017-08-04 11:13


起源

好问题... - RAJ


答案:


添加一些调试输出到 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

路径按此顺序尝试,第一个匹配的是将要使用的路径。


11
2017-08-04 16:34





尝试这个:

en:
  activerecord:
    errors:
      models:
        identity:
          attributes:
            identity:
              blank: 'Your new error message here'

-1
2017-08-04 11:48



这会将错误消息转换为ok,但我想翻译属性名称。 - starfry


您可以在db属性名称前面提供已翻译的值。

en:
  activerecord:
    attributes:
      identity: # this is model name
        identity: "translated attribute name"

您可能想要阅读有关活动模型的更多信息 属性本地化


-1
2017-08-04 12:39



你确定?我明白了 can not load translations from ...: #<Psych::SyntaxError: (...): did not find expected key while parsing a block mapping at line 126 column 13>。我不认为这是有效的yaml。 - starfry
是的,你是对的,看看更新的答案 - RAJ
不适合我。我在rails console中试过了 I18n.t 'activerecord.errors.attributes.identity.identity' 并返回预期值(所以我的yml是正确的)但该属性未在错误消息中进行翻译:( - starfry
activerecord.attributes.identity.identity 也不起作用。在攻击activemodel代码以查看它正在做什么之后,我发现所需要的是yml activerecord.attributes.identities.identity。我将在答案中提供更多细节。 - starfry