いつも忘れるため、Railsアプリをつくるときの日本語化の手順を整理した。
環境
$ rails -v Rails 6.0.3.2 $ ruby -v ruby 2.7.1
手順
多言語化対応のための rails-i18n をインストール。
gemfile
gem "rails-i18n"
config/application.rb
~ # Application configuration can go into files in config/initializers # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. #追記 config.time_zone = "Tokyo" config.i18n.default_locale = :ja end end
日本語のロケールファイルをつくる。
touch config/locales/ja.yml
翻訳情報を入力していく。
config/locales/ja.yml
ja: date: formats: default: "%Y年%m月%d日" ym_jp: "%Y年%m月" ym: "%Y%m" ymd_hy: "%Y-%m-%d" da_jp: "%e日(%a)" short: "%Y/%m/%d" md: "%m月%d日" sm: "%m/%d" time: formats: default: "%Y年%m月%d日(%a) %H:%M" short: "%Y/%m/%d %H:%M" time_only: "%H:%M" date_only: "%m月%d日" date_and_time: "%m月%d日%H:%M" activerecord: models: user: ユーザー attributes: user: name: 名前 email: Email attributes: created_at: 作成日時 updated_at: 更新日時 link: edit: 編集 show: 詳細 destroy: 削除 back: 戻る
たとえば、Userモデルがあって、属性にnameとemailがあったとすると、このように設定する。
〜 activerecord: models: user: ユーザー attributes: user: name: 名前 email: Email 〜
viewで使う方法
Userモデルの属性名を使う場合。もしMemberモデルなら、Member.human_attribute_name(:hoge)
になる。
<%= User.human_attribute_name(:name) %> <%= User.human_attribute_name(:email) %>
モデル以外でロケールファイルの翻訳情報を使いたい場合。
<td><%= link_to t("link.show"), user %></td> <td><%= link_to t("link.edit"), edit_user_path(user) %></td>
関連:Railsのモデル属性やエラーメッセージなどを日本語で表示する方法 - Just do IT
参考
他のプロジェクトはどうしているのかを見ると参考になる。