Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Rails: Status Using ActiveRecord::Enum

Rails: Status Using ActiveRecord::Enum

In Rails we can easily assign and switch the status of an object using ActiveRecord::Enum.

class Post < ActiveRecord::Base
  enum status: { active: 0, archived: 1 }
end! # => true
post.status  # => "active"

post.archived? # => true
post.status    # => "archived"

post.status = "archived"
post.status # => "archived"

post.status = nil
post.status.nil? # => true
post.status      # => nil

Scopes are provided.

Post.where(status: [:active, :archived])
Post.where.not(status: :active)

For ActiveRecord::Enum to work we need to create a status column with a type of integer and a default value of 0.

Example migration:

class AddStatusToPosts < ActiveRecord::Migration[5.2]
  def change
    add_column :posts, :status, :integer, default: 0


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.