今回はaccept_nested_attributes_forのエラーメッセージを日本語化する方法についてまとめたいと思います。ja.ymlの記述が一般モデルの日本語化の方法とは少し異なっていたので、自分の備忘録としても残しておきます。
accepts_nested_attributes_forの日本語化
前提
以下のようなaccept_nested_attributes_forを用いた親子孫関係があるとします。
class Parent < ApplicationRecord
has_many :children
accepts_nested_attributes_for :children
end
class Child < ApplicationRecord
belongs_to :parent
has_many :grand_children
accept_nested_attributes_for :grand_children
end
class GrandChild < ApplicationRecord
belongs_to :child
end

日本語化の手順
日本語化の手順はいたって簡単ですが、ja.ymlで親子孫関係は/(スラッシュ)で区切らなければならないという点だけ注意してください。
# config/application.rbに以下を追記
config.i18n.default_locale = :ja
# config/locals/ja.ymlに以下の記述を追記
ja:
activerecord:
attributes:
parent:
name: '親の名前'
parent/children:
name: '子の名前'
parent/children/grand_children:
name: '孫の名前'
ja.ymlを以下のように記載しても日本語化されないので注意してください。
ja:
activerecord:
attributes:
parent:
name: '親の名前'
children:
name: '子の名前'
grand_children:
name: '孫の名前'
日本語化の手順まとめ
- config/application.rbに日本語設定を追記
- ja.ymlで日本語化したいカラム名を記載(親子孫関係は/スラッシュで区切る)
参考
accepts_nested_attributes_forしたときのi18n
今回はaccept_nested_attributes_forのエラーメッセージを日本語化する方法についてまとめました。accept_nested_attributes_forは非推奨メソッドですが、使用した際の参考になればと思います。