我在翻译嵌套模型的错误消息时遇到问题。
假设我们有一个父类Foo
,它接受Bar
的属性:
class Foo < ActiveRecord::Base
has_many :bars
accepts_nested_attributes_for :bars
validates_associated :bars
end
class Bar < ActiveRecord::Base
belongs_to :foo
validates :a, presence: true
end
如果我使用无效Foo
创建Bar
,则会验证bars
(请注意错误消息中的复数名称bars
):
foo = Foo.new(bars_attributes: [b: 'something'])
foo.valid?
foo.errors.messages
=> {:"bars.a"=>["must be present"] }
翻译时,I18n
似乎正在寻找翻译文件中关联名称(bars
复数形式)的翻译而不是单数模型名称(bar
) (例如瑞典语)config/local/sv
:
sv:
activerecord:
attributes:
bar:
a: 'The normal place for the translation'
bars:
a: 'The place where I18n is using when nested with Foo'
显然我不想两次说出我的翻译,我想摆脱配置中的最后两行。
为查找嵌套模型的翻译时,为什么I18n
使用关联名称?我错过了什么吗?
答案 0 :(得分:3)
我不确定可以帮助使用关联名称。但我可以为你提供部分解决方案:
sv:
activerecord:
attributes:
bar: &bar
a: 'The normal place for the translation'
bars: *bar
编辑:&identifier
设置引用前一个哈希的锚点,而*identifier
允许您引用该锚点。在这种情况下,“* bar”引用将采用“bar”底层结构并将其包含在“bars”中。
请查看此快速指南:http://rhnh.net/2011/01/31/yaml-tutorial 当然,您也可以尝试精心制作的YAML文档或此Wiki页面:https://en.wikipedia.org/wiki/YAML