Reputation: 509
I have problem translating error messages for nested models.
Lets say we have a parent class Foo
which accepts attributes for 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
If I create a Foo
with an invalid Bar
, it validates bars
(notice the plural name bars
in the error messages):
foo = Foo.new(bars_attributes: [b: 'something'])
foo.valid?
foo.errors.messages
=> {:"bars.a"=>["must be present"] }
When this is translated, I18n
seems to be looking for the translations for the association name (bars
in plural) instead of the singular model name (bar
) in the translation file (the Swedish one for instance) 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'
Obviously I do not want to state my translations twice, I want to get rid of the two last lines in the config.
Why is I18n
using the association name when looking for translation for the nested model? Am I missing something?
Upvotes: 1
Views: 820
Reputation: 831
I'm not sure the usage of association name can be helped. But i can offer you a partial solution:
sv:
activerecord:
attributes:
bar: &bar
a: 'The normal place for the translation'
bars: *bar
EDIT: The &identifier
sets up the anchor referencing the preceding hash, while *identifier
allows you to reference that anchor. In this scenario, the "*bar" reference will take the "bar" underlying structure and include it into "bars".
Take a look at this quick guide: http://rhnh.net/2011/01/31/yaml-tutorial Of course, you're also welcome to try the elaborate YAML docs or this wiki page: https://en.wikipedia.org/wiki/YAML
Upvotes: 4