LoginSignup
0
0

More than 1 year has passed since last update.

【Rails】enum_help使用してselectボックス作成

Last updated at Posted at 2021-11-04

検索すると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引数:クラスを定義する場合、空を指定しオプションはないことを明記

参考

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