如何在Ruby类/模块命名空间中翻译模型?

Viz*_*ack 42 localization namespaces model ruby-on-rails internationalization

我有一个型号Products :: Car.我该如何翻译其属性?

我已经尝试过了:

activerecord: 
  models:
    products:
      car: "??????????"
  attributes:
    products:
      car:
        owner: "????????"
Run Code Online (Sandbox Code Playgroud)

还有这个:

activerecord: 
  models:
    products_car: "??????????"
  attributes:
    products_car:
      owner: "????????"
Run Code Online (Sandbox Code Playgroud)

但如果我尝试使用Products :: Car.model_name.human,它仍然会说"Car".我的其他翻译工作得很好,语言设置为:ru.

Viz*_*ack 105

我检查了"model_name.human"源代码并找到了'i18n_key'方法.我试过这个:

irb(main):006:0> Products::Car.model_name.i18n_key
=> :"products/car"
Run Code Online (Sandbox Code Playgroud)

然后我将我的yml文件更改为:

activerecord:    
  models:
    products/car: "??????????"   
  attributes:
    products/car:
      owner: "????????"
Run Code Online (Sandbox Code Playgroud)

它的工作原理!

编辑:

如需进一步参考:i18n_key在初始化程序中设置了ActiveModel::Name https://github.com/rails/rails/blob/375a4143cf5caeb6159b338be824903edfd62836/activemodel/lib/active_model/naming.rb#L147

它只是基于

MyClass.name.underscore
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你分享这个. (5认同)