0
0

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 1 year has passed since last update.

enum

Posted at

enumのメリット

  • データの整合性と可読性の向上
  • データベースのスキーマの柔軟性
    これはかなり大きいと思います。例えば、booleanで設定すると、今後の選択肢が増えた場合に変更できなくなってしまいます。しかし、enumで設定しておくと後からのデータベース変更を柔軟に行うことができます。(まあ可能な限り変更しないことが理想ではあるんですが、、、)

マイグレーションファイルで列挙型を定義

rails g migration AddColumnStatusToUser
      invoke  active_record
      create  db/migrate/20230511075254_add_column_status_to_user.rb
class AddStatusToUsers < ActiveRecord::Migration[6.0]
  def change
    add_column :users, :status, :integer, default: 0
  end
end
rails db:migrate

モデルクラスで列挙型を定義

user.rb
class User < ApplicationRecord
  enum status: {
    waiting: 0,
    start: 1,
    processing: 2,
    done: 3
  }
end
pry(main)> task = Task.new
=> #<Task:0x00007fcf87e51a88 id: nil, name: nil, status: "waiting", created_at: nil, updated_at: nil>

pry(main)> task.status = 1
=> 1

pry(main)> task.status
=> "start"

pry(main)> task.status = 2
=> 2

pry(main)> task.status
=> "processing"

pry(main)> task.status = 3
=> 3

pry(main)> task.status
=> "done"

数値として比較する場合は、メソッド[カラム名]_before_type_castが必要になるみたい

irb(main):080:0* task1.progress
=> "start"
irb(main):081:0> task2.progress
=> "waiting"
irb(main):082:0> task1.progress_before_type_cast > task2.progress_before_type_cast
=> true
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?