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

【Rails】Enumを使う

Posted at

どんな時に使う?

カラムstatusの値が
0だったら未処理
1だったら進行中
2だったら処理済み
みたいな時に、いい感じに書くことができます。

定義

migrationファイル
def change
  add_column :orders, :status, :integer, default: 0 # デフォルト値は0に設定する
end
app/models/order.rb
class Order < ApplicationRecord
  enum status: { waiting: 0, working: 1, completed: 2 }
end

できること

インスタンスを作成

order = Order.new(
          item: 'ボールペン',
          price: 150,
          status: 'working' # 今まで「1」と数値でセットしていた部分を文字列でセットできる。DBには「1」が保存される
        )

インスタンスの中身を確認

pry(main)> order.status
=> "working"
pry(main)> order.working?
=> true 
pry(main)> order.completed?
=> false

インスタンスを更新

pry(main)> order.status
=> "working"
pry(main)> order.completed!
=> "completed"
pry(main)> order.status
=> "completed"

DBを検索

pry(main)> completed_orders = Order.completed
=> SELECT `orders`.* FROM `orders` WHERE `orders`.`status` = 2 LIMIT 11

複数カラムで同じ名前を使いたい場合

こういう場合
class Order < ApplicationRecord
  enum hoge_status: { waiting: 0, working: 1, completed: 2 }
  enum fuga_status: { waiting: 0, working: 1, completed: 2 }
end

Order.waiting?としても、hoge_statusfuga_statusのプログラムはどちらを見れば良いかわかりません。
こういった場合、_prefix: trueを使って解決します。

prefixで解決
class Order < ApplicationRecord
  enum hoge_status: { waiting: 0, working: 1, completed: 2 }, _prefix: true
  enum fuga_status: { waiting: 0, working: 1, completed: 2 }, _prefix: true
end
pry(main)> Order.hoge_status_completed?
=> SELECT `orders`.* FROM `orders` WHERE `orders`.`hoge_status` = 2 LIMIT 11
`
pry(main)> Order.fuga_status_completed?
=> SELECT `orders`.* FROM `orders` WHERE `orders`.`fuga_status` = 2 LIMIT 11

参考

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?