【问题标题】:Rails i18n - How to translate model in fields_for that has_one inherited modelRails i18n - 如何在 fields_for 中为 has_one 继承模型翻译模型
【发布时间】:2020-04-30 22:41:30
【问题描述】:

我有以下型号:

class AccountMovement < ActiveRecord::Base
  has_one :accounting_document
  ..
end

class AccountingDocument < ActiveRecord::Base
  belongs_to :account_movement
  ..
end

class CreditNote < AccountingDocument
  ..
end

class Invoice < AccountingDocument
  ..
end

用户可以添加信用票据

<%= form_with model: @credit |f| %>

  <%= f.fields_for :account_movement do |ff| %>
    <div>
      <%= ff.label :amount %>
      <%= ff.number_field(:amount, step: 0.01, autofocus: true) %>
    </div>
    ...
  <% end %>
  ...
<% end %>

网站只支持葡萄牙语,所以我添加了以下翻译

pt:
  activerecord:
    attributes:
      account_movement:
        amount: 'Valor'

但它无法自动翻译 account_movement 的金额属性。当表单看起来像这样时,这适用于 has_one 关系

<%= form_with model: @account_movement |f| %>

  <div>
    <%= f.label :amount %>
    <%= f.number_field(:amount, step: 0.01, autofocus: true) %>
  </div>

  <%= f.fields_for :credit_note do |ff| %>
    ...
  <% end %>

  ...
<% end %>

我已经尝试了很多方法都没有成功

pt:
  activerecord:
    attributes:
      account_movement:
        amount: 'Valor'
      credit_note/account_movement:
        amount: 'Valor'
      credit_note[account_movement]:
        amount: 'Valor'
      credit_note_account_movement:
        amount: 'Valor'

我是否遗漏了某些内容或不支持在 fields_for 中自动翻译反向 has_onde 关系?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-5 rails-i18n


    【解决方案1】:

    我发现了问题。它在AccoutingDocument 处缺少accepts_nested_attributes_for :account_movement

    class AccountingDocument < ActiveRecord::Base
      belongs_to :account_movement
    
      accepts_nested_attributes_for :account_movement
      ..
    end
    

    不需要在本地添加额外的翻译

    pt:
      activerecord:
        attributes:
          account_movement:
            amount: 'Valor'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多