やったこと
ActiveRecord の enum を使ってみます。
確認環境
$ ruby --version
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin17]
$ rails --version
Rails 5.2.3
調査
準備
$ rails g model book title:string status:integer
$ rails db:migrate
enum の項目だけ定義する場合
app/models/book.rb
class Book < ApplicationRecord
enum status: [ :nothing, :doing, :done ]
end
コンソール
irb(main):004:0> Book.statuses
=> {"nothing"=>0, "doing"=>1, "done"=>2}
-- データ作成
irb(main):005:0> Book.create(title: 'book1', status: 1)
(0.1ms) begin transaction
Book Create (0.8ms) INSERT INTO "books" ("title", "status", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["title", "book1"], ["status", 1], ["created_at", "2020-03-14 07:35:38.468498"], ["updated_at", "2020-03-14 07:35:38.468498"]]
(1.5ms) commit transaction
=> #<Book id: 1, title: "book1", status: "doing", created_at: "2020-03-14 07:35:38", updated_at: "2020-03-14 07:35:38">
-- データ取得
irb(main):006:0> b = Book.find(1)
Book Load (0.2ms) SELECT "books".* FROM "books" WHERE "books"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
=> #<Book id: 1, title: "book1", status: "doing", created_at: "2020-03-14 07:35:38", updated_at: "2020-03-14 07:35:38">
-- stauts を更新
irb(main):007:0> b.done!
(0.1ms) begin transaction
Book Update (0.6ms) UPDATE "books" SET "status" = ?, "updated_at" = ? WHERE "books"."id" = ? [["status", 2], ["updated_at", "2020-03-14 07:38:35.150818"], ["id", 1]]
(0.9ms) commit transaction
=> true
enum で key と value を定義する場合
app/models/book.rb
class Book < ApplicationRecord
enum status: { nothing: 0, doing: 2, done: 4 }
end
コンソール
-- データ取得
irb(main):011:0> b = Book.find(1)
Book Load (0.1ms) SELECT "books".* FROM "books" WHERE "books"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
=> #<Book id: 1, title: "book1", status: "doing", created_at: "2020-03-14 07:35:38", updated_at: "2020-03-14 07:38:35">
irb(main):012:0> b.status
=> "doing"
-- データ更新
irb(main):013:0> b.done!
(0.1ms) begin transaction
Book Update (0.3ms) UPDATE "books" SET "status" = ?, "updated_at" = ? WHERE "books"."id" = ? [["status", 4], ["updated_at", "2020-03-14 07:42:16.748137"], ["id", 1]]
(1.0ms) commit transaction
=> true
enum をメソッドみたいに使えるの知りませんでした。