Railsのenum機能を使う

railsenum機能を使ってみた。

class Test
  enum type: { todo: 'Todo', doing: 'Doing', done: 'Done' }
end

この場合

色々なサイトに書かれている通り以下のメソッドが使える

Test.todo # typeが'Todo'のものの一覧を返すSQL=>
SELECT "tests".* FROM "tests"  WHERE "tests"."type" = 'Todo'  ORDER BY "tests"."id" DESC

@test = Test.find(1)
@test.doing? # typeが'Doing'だとtrueを返す
@test.done! # typeを'Done'に変更するSQL=>
  (0.2ms)  BEGIN
  SQL (6.6ms)  UPDATE "tests" SET "type" = $1, "updated_at" = $2 WHERE "tests"."id" = 1  [["type", "Done"], ["updated_at", "2014-12-09 00:59:24.600051"]]
   (2.7ms)  COMMIT
=> true