Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
293
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

Rails enumについてまとめておく

Railsにおけるenumの使い方

enumのカラムのカラム追加

integer

class AddStatusToArticles < ActiveRecord::Migration
  def change
    add_column :articles, :status, :integer, default: 0
    add_index :articles, :status # 必要に応じて
  end
end

boolean

class AddStatusToArticles < ActiveRecord::Migration
  def change
    add_column :articles, :status, :boolean, default: false
    add_index :articles, :status # 必要に応じて
  end
end

Modelへの定義

integer

class Article < ActiveRecord::Base
  enum status: { draft: 0, published: 1 }
end

boolean

class Article < ActiveRecord::Base
  enum status: { draft: false, published: true }
end

配列での定義 (integer)

class Article < ActiveRecord::Base
  enum status: [:draft, :published]
end

DBの値は要素番号と同じになる。ただし、適当に要素を追加するとDBの値と齟齬が生じてしまうため注意。

enumのメソッド

integer (hash定義)

article = Article.new(status: :draft)
# article = Article.new(status: 0) これでもいける

article.status # => draft
article.draft? # => true
article.published? # => false

article.published! # statusをpublishedに変更

Article.statuses # => { draft: 0, published: 1 }
# article = Article.new(status: Article.statuses[:draft]) のように使える

Article.published
# publishedの検索が出来る。
# Article.where(status: :published) でも。

boolean

integerとほぼ一緒。

article = Article.new(status: :draft)
# article = Article.new(status: false) これでもいける

article.status # => draft
article.draft? # => true
article.published? # => false

article.published! # statusをpublishedに変更

Article.statuses # => { draft: false, published: true }
# article = Article.new(status: Article.statuses[:draft]) のように使える

Article.published
# publishedの検索が出来る。
# Article.where(status: :published) でも。

参考

↓まとめてあった。
いまさらながらRails4.1から導入されたEnumが便利なのでまとめてみた

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
293
Help us understand the problem. What are the problem?