【问题标题】:How can I use a nested attribute's translation in a label so I only maintain one translation?如何在标签中使用嵌套属性的翻译,以便我只维护一个翻译?
【发布时间】:2020-12-05 23:22:14
【问题描述】:

对 i18n 非常陌生,如果这很简单,请原谅,但我无法在任何地方找到问题的答案。

我有 n 个模型,belong_to: location

我想为location 分配一个翻译,这样当父对象显示他们的子location 时,翻译就会出现。

型号

class Model1 < ApplicationRecord
  belongs_to: location
class Model2 < ApplicationRecord
  belongs_to: location
.
.
.
class ModelN < ApplicationRecord
  belongs_to: location

class Location < ApplicationRecord
  has_many: model1s
  has_many: model2s
  has_many: modelNs

观看次数 Model1 创建视图

<%= form_with(model: model1, local: true) do |form| %>
.
.        
   <td><%= form.label :location %></td>
   <td><%= form.select(:location_id, @location_options) %></td>

Model2 创建视图

<%= form_with(model: model2, local: true) do |form| %>
.
.        
   <td><%= form.label :location %></td>
   <td><%= form.select(:location_id, @location_options) %></td>

我尝试分配全局标签以及模型名称。都没有用。

fr.yml

fr:
  helpers:
    label:
      location: 'Emplacement'
  activerecord:
    models:
      location:
        one: 'Emplacement'
        other: 'Emplacements'

当我将翻译分配给 Create 提交帮助程序时,它会在全局范围内应用(甚至不必在 t.(...) 之前。我希望这与 form.label 类似,但可惜,它没有。有吗一种为表示嵌套对象名称的标签全局分配翻译的方法?

【问题讨论】:

    标签: ruby-on-rails internationalization


    【解决方案1】:

    您可以在 YAML 中创建一个公共块:

    fr:
      common: &common_values
        location:
          one: 'Emplacement'
          other: 'Emplacements'
    
      activerecord:
        models:
          model1:
            <<: *common_values
            name: 'Model 1'
          model2:
            <<: *common_values
            name: 'Model 2'
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      • 2014-09-18
      • 1970-01-01
      • 2016-05-01
      • 2022-08-18
      相关资源
      最近更新 更多