検索するとmapを使っているやり方がほとんどだったがこっちの方がシンプルに書ける
環境
Ruby 3.0.2
Rails 6.1.4.1
やり方
enum_help使用
model.rb
class Employee < ApplicationRecord
enum status: { enrollment: 0, resigned: 1 }
end
-
Employee.statuses_i18n
はenum_helpで使えるようになるもの
Employee.statuses_i18n
# => {"enrollment"=>"在職中", "resigned"=>"退職済み"}
html.slim
f.collection_select :status, Employee.statuses_i18n.to_a, :first, :last, {}, class: 'hogehoge'
f.collection_select(メソッド名, オブジェクトの配列, value属性の項目, テキストの項目 [, オプション or HTML属性 or イベント属性])
第2引数:配列指定
第3引数(value属性の項目):配列の最初の要素(ここでいうと"enrollment", "resigned")
第4引数(テキストの項目):配列の最後の要素(ここでいうと"在職中", "退職済み")
第5引数:クラスを定義する場合、空を指定しオプションはないことを明記
参考