平々凡々エンジニア

平凡で難しい悩みを解決

rails gem I18n を使用したエラーメッセージの日本語化

railsチュートリアルではユーザー登録入力フォームなどのエラーメッセージの内容は全て英語だったので

日本語化に挑戦したいと思います。

以下に日本語化前の表示とソースを示します。

f:id:ceratophrysgerogero:20191111142710p:plain


new.html.erb

<% provide(:title, 'ユーザー登録') %>
<h1> ユーザー登録</h1>

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for(@user) do |f| %>
      <%= render 'shared/error_messages' %>

      <%= f.label :name %>
      <%= f.text_field :name, class: 'form-control' %>
  
      <%= f.label :email %>
      <%= f.text_field :email, class: 'form-control'  %>
  
      <%= f.label :password %>
      <%= f.text_field :password, class: 'form-control'  %>
  
      <%= f.label :password_confirmation %>
      <%= f.text_field :password_confirmation, class: 'form-control'  %>
  
      <%= f.submit "アカウント作成", class: "btn btn-primary"%>
   
    <% end %>
  </div>
</div>


views/shared/_error_messages.html.erb

<% if @user.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-danger">
      <%= @user.errors.count %>個の入力エラーがあります
    </div>
    <ul>
    <% @user.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
<% end %>


日本語化方法

gem 'rails-i18n'をbundle install

config/application.rbconfig.i18n.default_locale = :jaをクラス内に追加

これでモデル以外の日本語化ができます。 モデル名の日本化はymlファイルに出力したいモデル名を記載します。

私の場合

config/locales/models/ja.yml

ja:
  activerecord:
    models:
      user: ユーザー
    attributes:
      user:
        name: 名前 
        email: メールアドレス
        password: パスワード
        password_confirmation: パスワード確認

としました。

models: はモデル名、attributes: はモデルの attributeの訳になります。

このファイルを読み込むために config/application.rbに以下の内容をクラス内に書き込みます。

config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.yml').to_s]

これは正規表現を使用したconfig/locales以下のディレクトリ内にある全てのymlファイルを読み込むように指示するものになります。

するとエラー内容だけではなくなりlabelに記載されているものまで 動的に和訳することができます。

f:id:ceratophrysgerogero:20191111145010p:plain