340
299

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 5 years have passed since last update.

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

Posted at

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

340
299
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
340
299

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?