7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Ruby on Rails】enumを日本語表記にする方法

Posted at

目標

enumでの表記を日本語にする

開発環境

ruby 2.5.7
Rails 5.2.4.3
OS: macOS Catalina

前提

※ ▶◯◯ を選択すると、説明等が出てきますので、
  よくわからない場合の参考にしていただければと思います。

流れ

1 gemを導入
2 config/application.rbを編集
3 config/locales/ja.ymlを作成、編集
4 viewを変更

gemを導入

今回はgem 'rails-i18n'とgem 'enum_help'を導入します。

Gemfile
gem 'rails-i18n'
gem 'enum_help'
ターミナル
$ bundle install

config/application.rbを編集

config.load_defaults以下4行を追記。

config/application.rb
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.2
    config.paths.add 'lib', eager_load: true
    config.time_zone = 'Tokyo'
    config.i18n.default_locale = :ja
    config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]

    # Settings in config/environments/* take precedence over those specified here.
    # 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.
  end

config/locales/ja.ymlを作成、編集

config/locales配下にja.ymlを作成。

config/locales/ja.yml
ja:
  enums: 
    talk: # モデル名
      contributor: # カラム名
        customer: '会員' # enumの値
        shop: '店舗' # enumの値
        admin: '管理者' # enumの値
    customer: # モデル名
      privacy: # カラム名
        published: 公開 # enumの値
        closed: 非公開 # enumの値

viewを変更

_i18nを日本語表記にしたいカラムの後に追加。

app/views/homes/about.html.erb
<%= @talk.contributor_i18n %>

補足

エラーの日本語表記についてはこちら
更新日、作成日を好みの表記についてはこちら

7
4
0

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
7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?