LoginSignup
81
80

More than 5 years have passed since last update.

I18n でネストしたモデルの属性名の対応

Last updated at Posted at 2015-01-29

I18n の基本的な使い方は、下記でまとめたんだけど、その中でネストしたモデルの場合に翻訳できなかったので、調べて実装した時のメモです。

Rails で I18n を使って日本語化

ネストした (名前空間を切った) モデルの場合

モデル例

class User < ActiveRecord::Base
  attr_accessible :name, :posts_attributes

  has_many :posts
end

class User::Post < ActiveRecord::Base
  attr_accessible :title, :body

  belongs_to :user, class_name: User::Post
end

書き方

ja:
  activerecord:
    attributes:
      user:
        id: ID
        created_at: 登録日時
        updated_at: 更新日時
        birthday: 生年月日
        email: メールアドレス
      user/post:
        title: タイトル
        body: 本文

accepts_nested_attributes_for を設定しているモデルの場合

accepts_nested_attributes_for で他のモデルの属性を受け取れるようにしている場合には、
下記のように書けば、合わせて翻訳してくれる

モデル例

class User < ActiveRecord::Base
  attr_accessible :name, :posts_attributes

  has_many :posts
  accepts_nested_attributes_for :posts
end

class Post < ActiveRecord::Base
  attr_accessible :title, :body

  belongs_to :user
end

辞書ファイルの書き方

ja:
  activerecord:
    attributes:
      user:
        id: ID
        created_at: 登録日時
        updated_at: 更新日時
        birthday: 生年月日
        email: メールアドレス
      user/posts:
        title: タイトル
        body: 本文

もちろん、Post 単体を作成した際の validate エラー等を翻訳する場合は、下記のように個別に post で辞書ファイルに追記が必要

ja:
  activerecord:
    attributes:
      user:
        id: ID
        created_at: 登録日時
        updated_at: 更新日時
        birthday: 生年月日
        email: メールアドレス
      user/posts:
        title: タイトル
        body: 本文
      post:
        title: タイトル
        body: 本文

上記との相違は、Post 名前空間を切っていない has_many のアソシエーションのため、user/posts: と表記が複数形になっている

参考URL:
http://journal.sooey.com/194

81
80
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
81
80