i18nによる日本語化対応の設定
①config/application.rbに以下の設定を追加
config.i18n.available_locales = %i[ja en] #アプリケーションが対応している言語の設定(ja=日本語、en=英語) config.i18n.default_locale = :ja #デフォルトの言語を日本語に設定 config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s] #言語ファイルを階層ごとに設定できるようにするための設定
②gemファイルにgemを追加
gem 'rails-i18n'
③gemをインストール
$ bundle install
④config/localesの中にja.ymlファイルを追加し、情報を定義します
(アプリケーションが増えると1つのファイルで管理がしづらくなるので、↓のようにActiveRecordとViewで分けて作成することも可能)
※ymlファイルのインデントが少しずれているだけでもエラーになってしまうので、注意!
ja: activerecord: models: user: 'ユーザー' board: '掲示板' attributes: user: last_name: '姓' first_name: '名' email: 'メールアドレス' password: 'パスワード' password_confirmation: 'パスワード確認'
ja: defaults: login: 'ログイン' register: '登録' logout: 'ログアウト' users: new: title: 'ユーザー登録' to_login_page: 'ログインページへ' user_sessions: new: title: 'ログイン' to_register_page: '登録ページへ' password_forget: 'パスワードをお忘れの方はこちら' boards: index: title: '掲示板一覧' new: title: '掲示板作成' bookmarks: title: 'ブックマーク一覧' profiles: show: title: 'プロフィール'
⑤viewに表示させる
<%= t('activerecord.models.user') %>
例えば↑のように埋め込みをするとビューでは「ユーザー」と表示されます
form_withはちょっと特殊
上に習うと、form_withの中で使おうとした時に下記のような表記になります。
<%= form_with model: @user, local: true do |f| %> <%= f.label :email, t('activerecord.attributes.user.email') %> <%= f.email_field :email' %>
しかし、model: @user
から勝手に「これはユーザーに関する記述だ」と判断してくれるため、以下のように省略することも可能です。
<%= form_with model: @user, local: true do |f| %> <%= f.label :email %> <%= f.email_field :email %>
human_attribute_nameとModel.model_name.human
ActiveRecord::Baseのクラスメソッド。多言語化対応が可能になる。
まだよく理解しきれていないので、改めて理解できたら更新します。
↓何となくわかっていること
User.model_name.human # t(’activerecord.models.user’)と同じ
→「ユーザー」と表示される
User.human_attribute_name :email # t('activerecord.attributes.user.email')と同じ
→「メールアドレス」と表示される