Rails 嵌套模型错误翻译
Rails nested models error translation
我在翻译嵌套模型的错误消息时遇到问题。
假设我们有一个父 class 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
如果我创建一个带有无效 Bar
的 Foo
,它会验证 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
在查找嵌套模型的翻译时使用关联名称?我错过了什么吗?
我不确定关联名称的使用是否有帮助。但我可以为您提供部分解决方案:
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
我在翻译嵌套模型的错误消息时遇到问题。
假设我们有一个父 class 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
如果我创建一个带有无效 Bar
的 Foo
,它会验证 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
在查找嵌套模型的翻译时使用关联名称?我错过了什么吗?
我不确定关联名称的使用是否有帮助。但我可以为您提供部分解决方案:
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