Railsのモデル属性やエラーメッセージなどを日本語で表示する方法
モデルクラスの属性やエラーメッセージを日本語にするための、日本語訳ファイルが必要となる。 よって、wgetで以下のURLに記載されている翻訳ファイルをダウンロードする。
中身を見てみると、翻訳情報がたくさん載っている。 https://raw.githubusercontent.com/svenfuchs/rails-i18n/master/rails/locale/ja.yml
wget https://raw.github.com/svenfuchs/rails-i18n/master/rails/locale/ja.yml -P config/locales/
config/locales/ja.yml
というファイルが作られる。
さきほどのURLに掲載されていた翻訳情報がコピーされているのがわかる。
そもそもwgetコマンドがないと言われる場合
ちなみにMac/Homebrew環境でやっている。
-bash: wget: command not found
wgetコマンドをインストール。
brew install wget
これでOK。
locale.rbファイルを作成する
config/initializers/locale.rb
というファイルを作成する。
touch config/initializers/locale.rb
そして以下を記入。
Rails.application.config.i18n.default_locale = :ja
面倒なのでechoコマンドを使って出力してもいい。
echo "Rails.application.config.i18n.default_locale = :ja" > config/initializers/locale.rb
ちなみに、リダイレクト時の>
は上書き、>>
は追記という意味になる。今回は新規ファイル作成のため、>
でOK。
モデルの属性を日本語にしたい
つまり、これを
このように、自動で日本語にしたい。
そのために、モデル属性の翻訳情報を追加する。
config/locales/ja.yml
に、次の情報を記載。
models: task: タスク attributes: task: id: ID name: 名称 description: 詳しい説明 created_at: 登録日時 updated_at: 更新日時
具体的な挿入箇所はこちら。
ja: activerecord: errors: messages: record_invalid: 'バリデーションに失敗しました: %{errors}' restrict_dependent_destroy: has_one: "%{record}が存在しているので削除できません" has_many: "%{record}が存在しているので削除できません" # ここから models: task: タスク attributes: task: id: ID name: 名称 description: 詳しい説明 created_at: 登録日時 updated_at: 更新日時 # ここまで date: abbr_day_names:
もしモデルを増やした場合、上記に追記していけばいい。
models: task: タスク comment: コメント
属性(attributes)も同様。
view側の表記を変える
登録したモデルクラスの属性をview側で自動で日本語に変えるには、ヘルパーを使う。
<th><%= Book.human_attribute_name(:title) %></th> <th><%= Book.human_attribute_name(:memo) %></th> <th><%= Book.human_attribute_name(:author) %></th>
モデルクラス名.human_attribute_name(:属性名) => Book.human_attribute_name(:title)
こんなふうに書けば、登録したモデルクラスの属性(日本語)がviewで勝手に英語から日本語に変えてくれる。
失敗したやり方
URL間違い
指定したURLが間違っていた。
wget https://githubusercontent.com/svenfuchs/rails-i18n/master/rails/locale/ja.yml --output-file=config/locales/ja.yml
これをした後、config/locales/ja.yml
を確認してもこんな内容になっている。
--2020-01-23 11:17:00-- https://githubusercontent.com/svenfuchs/rails-i18n/master/rails/locale/ja.yml githubusercontent.com (githubusercontent.com) をDNSに問いあわせています... 失敗しました: nodename nor servname provided, or not known. wget: ホストアドレス `githubusercontent.com' を解決できませんでした。
できてない。ちなみにこれ、「現場で使える Ruby on Rails 5速習実践ガイド」に載っている方法である・・・。
以下が正解だった。
wget https://raw.github.com/svenfuchs/rails-i18n/master/rails/locale/ja.yml -P config/locales/
ちなみに、-P
の意味はこちら。
-P, --directory-prefix=PREFIX ファイルを PREFIX/ 以下に保存する
つまり、config/locales/
以下にhttps://raw.github.com/svenfuchs/rails-i18n/master/rails/locale/ja.yml
を保存するという意味になる。
ja.ymlのインデント間違い
モデル属性の翻訳情報を登録したとき、次のようなインデントになっていた。
models: task: タスク attributes: task: id: ID name: 名称 description: 詳しい説明 created_at: 登録日時 updated_at: 更新日時
正解はこう。
models: task: タスク attributes: task: id: ID name: 名称 description: 詳しい説明 created_at: 登録日時 updated_at: 更新日時
task:
以下のインデントを一段深くする。
理由は、taskモデルの属性がidやnameだから。インデントが深くなければ、taskやid, nameなどが同列に認識されてしまう。