LoginSignup
32
23

More than 5 years have passed since last update.

RailsのFormオブジェクトの日本語化

Last updated at Posted at 2017-01-24

ちょっとハマったのでメモ。

環境

  • Ruby 2.3.0
  • Rails s5.0

やりたかったこと

独自に定義したFormオブジェクトの日本語化したい。

原因とその対応

例えば以下のようなFormオブジェクトを作成したときに、

app/models/forms/share.rb

class Forms::Share
  include ActiveModel::Model
  attr_accessor :group_id, :user_id
end

ja.ymlにてactiverecordアトリビュート以下に書いても反映されない。

ja:
  activerecord:
    attributes:
        forms/share:
            group_id: グループ
            user_id: ユーザー

正しくは、activemodelアトリビュート以下に書く。

ja:
  activemodel:
    attributes:
        forms/share:
            group_id: グループ
            user_id: ユーザー

調べ方

bundle openでActiveModelを開いて、human_attribute_nameメソッドあたりをにbinding.pryを置いて動作を調べた。

module ActiveModel
  module Translation

    ~(省略)~

    def human_attribute_name(attribute, options = {})

      ~(省略)~

      options[:default] = defaults
      I18n.translate(defaults.shift, options)
    end

最後の行をhuman_attribute_nameメソッドの最後の行を実行してみると、

> I18n.translate(defaults.shift, options)
=> "translation missing: ja.attributes.group_id"

"translation missing"が発生しているので日本語化できていないんだなと。で、そのパラメータを見てみると、

> defaults.shift
=> :"activemodel.attributes.forms/share.group_id"

activemodel.attributesという値を渡していることがわかり、ja.ymlの設定ミスに気づいたのでした。

参考にした記事

原因の調べ方のあたり特に参考になりました。

Railsのvalidate周りのi18n対応でハマったこと

32
23
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
23