Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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が便利なのでまとめてみた

shizuma
web&DeepLearningエンジニア。 ACES.inc←東京大学大学院/東京←鹿児島/blog https://blog.seishin55.com ; Qiita https://qiita.com/shizuma ; note https://note.mu/seishin55
https://seishin55.com
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした