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 # => nilScopes 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
endReference: https://api.rubyonrails.org/v5.2/classes/ActiveRecord/Enum.html