4
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 5 years have passed since last update.

enumをi18n対応させてselectの選択肢として表示させる

Posted at

TL;DR

Taskモデルにstatus属性があるとして

# app/models/task.rb
...
enum status: { not_stated_yet: 0, started: 1, completed: 2 }
...

翻訳ファイルは下記の通り

# config/locales/models/task/ja.yml
ja:
	activerecord:
		models:
			task: タスク
		attributes:
			task:
				status: 対応状況
				detail: 内容
				due_on: 締め切り
	enums:
		task:
			type:
				not_stated_yet: 未着手
				started: 着手
				completed: 完了

ビューファイル内で以下のようにして表示させる

<%= select :task, :type, Task.types.map { |k, v| [t("enums.task.type.#{k}"), v] } %>

解説

enumの設定

enumカラムの追加

class AddTypeToTasks < ActiveRecord::Migration
  def change
    add_column :tasks, :status, :integer, default: 0
  end
end

マイグレーションの実行

$ bin/rails db:migrate

enumのモデルへの定義

# app/models/task.rb
...
enum status: { not_stated_yet: 0, started: 1, completed: 2 }
...

翻訳ファイルの作成

設定の追加

下記の設定を追加することでデフォルトで日本語の翻訳ファイルを読みに行ってくれる。
また、config/locales/配下のファイルを読み込んでくれるようになる。

# config/application.rb

...
config.i18n.default_locale = :ja
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s]

翻訳の追加

モデルの属性名の翻訳とenumの翻訳を追加する。

# config/locales/models/task/ja.yml
ja:
  activerecord:
    models:
      task: タスク
    attributes:
      task:
        status: 対応状況
        detail: 内容
        due_on: 締め切り
  enums:
    task:
      type:
        not_stated_yet: 未着手
        started: 着手
        completed: 完了

enumの翻訳の配置は好みの問題。
config/locales/ja.ymlの中に書いている人もいた。

自分の場合はモデルの翻訳ファイル内に書きたかったが、activerecordの翻訳とは分けたかったので上記の形に落ち着いた。

enum_helpというenumをI18n対応させてくれるgemもあったが、わざわざgemを入れるほどでもなかったので採用しなかった。

ただ、翻訳の配置はenum_helpのものを真似させていただいた。

ビューファイルでの呼び出し

以下の通り。

<%= select :task, :type, Task.types.map { |k, v| [t("enums.task.type.#{k}"), v] } %>

selectのタグ情報として配列を渡してあげると[key, value]として評価されるため、mapメソッドでenumの属性名をkey、値をvalueとして持つ配列を作成する。

参考

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