LoginSignup
56
47

More than 5 years have passed since last update.

ネストしたモデルでhuman_attribute_nameを使う

Posted at

モデルでの多言語対応

Railsのモデルでは、規則に沿った定義になっていればhuman_attribute_nameで多言語対応できる。
例えば、

ja.yml
ja:
  activerecord:
    attributes:
      user:
        name: 名前

だとすると


User.human_attribute_name :name
=> "名前"

app/models/以下に直接配置してあるような通常のモデルだとこれでOKだが、更にネストするようなモデルだと一工夫必要になる

ネストしたモデル

ActiveRecordの場合

例えば以下のような形であったとすると、

app/models/i18n_sample/a.rb

module I18nSample
  class A < ActiveRecord::Base
  end
end

localeファイルの構成は以下になる

ja:
  activerecord:
    attributes:
      i18n_sample/a:
        name: 名前A

結果は

I18nSample::A.human_attribute_name :name
=> "名前A"

モデル名に当たるキーは


I18nSample::A.model_name.i18n_key
=> :"i18n_sample/a"

で取得できるみたい

ActiveModelの場合

Rails4からはDBに保存しないモデルであってもActiveModelをincludeすることでValidation等の機能を追加することができる。
直接使用する機会が増えたような気がするActiveModelでも同じように対応するが、(あたりまえだけど)activerecordをactivemodelに変更しないと動かないのがハマりポイントだった。

module I18nSample
  class B
    include ActiveModel::Model
  end
end

だったとすると、

ja:
  activemodel:
    attributes:
      i18n_sample/b:
        name: 名前B
I18nSample::B.human_attribute_name :name
=> "名前B"

まとめ


ja:
  activemodel:
    attributes:
      i18n_sample/b:
        name: 名前B
  activerecord:
    attributes:
      user:
        name: 名前
      i18n_sample/a:
        name: 名前A

参考

ちなみにMongoIdとかでも同じように対応できるらしい(未確認)
http://apidock.com/rails/ActiveModel/Translation/human_attribute_name

56
47
0

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
56
47