0
2

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.

【Rails】enumの使い方

Last updated at Posted at 2020-04-28

開発環境

・Ruby: 2.5.7
・Rails: 5.2.4
・Vagrant: 2.2.7
・VirtualBox: 6.1
・OS: macOS Catalina

定義方法

boolean型

~.rb
enum is_valid: { '有効': true, '無効': false }

integer型

~.rb
enum drink: { '水': 0, 'お茶': 1, 'コーヒー': 2, 'お酒': 3 }

ビューでの使い方

1.プルダウン

~.html.erb
<%= f.select :drink, Menu.drinks.keys, include_blank: "-----" %>

<%= f.select :カラム名, モデル名.カラム名の複数形.keys, オプション %>

####②ラジオボタンで使用する場合

~.html.erb
<%= f.radio_button :is_valid, '有効', checked: true %>

<%= f.radio_button :カラム名, key, オプション %>

#default値について

enumを定義する場合、基本的にdefault値を設定しておく。

schema.rb
t.integer "drink", default: 0 # 初期値として'水'が設定される
0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?