Skip to content

Instantly share code, notes, and snippets.

@lujanfernaud
Last active October 30, 2018 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lujanfernaud/e355ee2cd01f4056abb69196326dce9f to your computer and use it in GitHub Desktop.
Save lujanfernaud/e355ee2cd01f4056abb69196326dce9f to your computer and use it in GitHub Desktop.
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