Skip to content

Instantly share code, notes, and snippets.

Embed
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

post.active!
post.active? # => true
post.status  # => "active"

post.archived!
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.active
Post.archived

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
  end
end

Reference: https://api.rubyonrails.org/v5.2/classes/ActiveRecord/Enum.html

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.