多个 Active Record 模型的属性翻译

Attribute translations for multiple Active Record models

我有几个相关但又不同的 AR 模型,它们包含代表相同数据的属性。当我为这些属性设置翻译时,我目前将它们设置为...

en:
  activerecord:
    attributes:
      model_a:
        assigned_date: "Assigned to worker"
      model_b:
        assigned_date: "Assigned to worker"
      [ ... ]

有没有办法以某种通配符方式定义此翻译一次

我认为最合理的方法...

en:
  activerecord:
    attributes:
      assigned_date: "Assigned to worker"
      model_a:
        [ model-specific translations here ]

不起作用,因为 AR 显然是在 attributes

下面的层中寻找型号名称

是的,您可以定义 "node anchors" 并在以后引用它们。此外,您可以重新定义 "node anchors" 部分中定义的属性,并根据您的要求使用不同的值。

使用如下:

en:
  activerecord:
    defaults: &defaults
      assigned_date: "Assigned to worker"
    attributes:
      model_a:
        <<: *defaults
        assigned_date: Model specific translation

在这种情况下,您定义节点锚 &defaults 并在 model_a 中引用它们。然后覆盖 model_aassigned_date 的值。所以,model_a.assigned_date 给你 "Model specific translation"。如果model_a下的assigned_date没有重新定义,model_a.assigned_date会给你"Assigned to worker".

公共属性可以上升一级并在需要时被覆盖

en:
    attributes:
        first_name: Name
    activerecord:
        attributes:
            user:
                email: Email
            admin:
                first_name: First Name