首页 > 解决方案 > 如何在 Rails 中显示索引翻译(rails-i18n)?

问题描述

Rails 5 使用(嵌套属性上的错误索引)为模型添加了错误索引:

class Order
    has_many :operations, index_errors: true

    accepts_nested_attributes_for :operations
end
class Operation
    has_many :inv_items, index_errors: true

    accepts_nested_attributes_for :inv_items
end

作为调用 order.errors.full_messages 的结果,我收到以下形式的错误:

{:"operations[0].inv_items[0].serial_num"=>["不能为空"], :"operations[0].inv_items[1].serial_num"=>["不能为空"]}

在文件 .yml 我可以直接设置翻译

en:
  activerecord:
    attributes:
      warehouse/order/operations[0]/inv_items[0]:
        serial_num: 'Serial number'

但是如何在不指明每个索引的情况下组织翻译呢?

标签: ruby-on-railsactiverecordindexingmessagerails-i18n

解决方案


尝试为模型设置翻译而不将其嵌套在其关联中。类似于下面的片段。

en:
  activerecord:
    models:
      inv_item: Inventory Item
    attributes:
      inv_item:
        serial_num: Serial Number

导轨指南


推荐阅读