LoginSignup
13
18

More than 3 years have passed since last update.

【Rails 5.2】i18nでenumを日本語化 & モデル(model)別にYMLファイルを管理

Last updated at Posted at 2018-07-13

STEP1 : Gemfile 設定

your_app/Gemfile
gem 'enum_help'

STEP2 : locale 設定

your_app/config/application.rb

module YourApplication
  class Application < Rails::Application

    # 以下追記
    config.time_zone = 'Tokyo'
    config.active_record.default_timezone = :local
    config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s]
    config.i18n.default_locale = :ja    


  end
end

STEP3 : ja ファイル設置

サンプルのモデルをUser、enum をsex_typeとします

config/locales/models/user/ja.yml
ja:
  activerecord:
    models:
      user: ユーザ情報
    attributes:
      user:
        sex_type: 性別
  enums:
    user:
      sex_type:
        male:男性
        female:女性

STEP4 : view で確認

<%= form_with(model: @user, local: true) do |form| %>
  <table>
    <tr>
      <th><%= form.label :sex_type %></th>
      <td>
        <%= form.select :sex_type, User.sex_types_i18n.keys.map { |k| [User.sex_types_i18n[k], k]} %>
      </td>
    </tr>
  </table>
<% end %>

参考

13
18
5

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
13
18