LoginSignup
2
1

More than 3 years have passed since last update.

[Rails]enumについて

Posted at

enumとは

ActiveRecordに定義されているメソッド。 enumを使うと、プログラムからは文字列でアクセスでき、データベースには整数値で保存される属性を作成できるメソッド。

記述例

まず、「status」カラムをinteger型で作成する。

20×××××××××××.rb
class CreateArticles < ActiveRecord::Migration
  def change
    create_table :articles do |t|
      t.integer :status, default: 0, null: false, limit: 1
      t.timestamps null: false
    end

    add_index :articles, :status
  end
end

次に、enum、属性名、属性の値(ハッシュ)で指定する。

user.rb

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

enumに使えるメソッド

enumで定義したハッシュのキー名+?とすることで、そのキーの値が設定されているか確認出来る。
また、キー名+!で新たに値を設定し、DBに保存出来る。


# articre.status = draftとした場合
article.draft?      # trueを返す

article.published!   # 新たに値を設定
2
1
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
2
1