How To Use Enums in Rails 6

1 min read Original article ↗

An enum is a data type made out of a set of named values. Let’s leverage them

Catalin Ionescu

Press enter or click to view image in full size

How to use enums in Ruby on Rails. Photo by the author.

In Ruby on Rails, an enum is an attribute where the values map to integers in the database and can be queried by name.

For example, we could define an enum for the status attribute, where the possible values are pending, active, or archived.

Ruby on Rails added support for enums in Rails 4.1.

Basic Usage of Enums in Rails

Adding an enum to an existing model is as simple as adding an integer column to that table. You can generate a new migration by using the following bash command:

$ bundle exec rails g migration AddStatusToUsers status:integers

This will generate the following migration:

class AddStatusToUsers < ActiveRecord::Migration[6.0]
def change
add_column :users, :status, :integer, default: 0
end
end

Run the migration using bundle exec rails db:migrate. In your User model, you need to define the enum as: