Press enter or click to view image in full size
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:integersThis will generate the following migration:
class AddStatusToUsers < ActiveRecord::Migration[6.0]
def change
add_column :users, :status, :integer, default: 0
end
endRun the migration using bundle exec rails db:migrate. In your User model, you need to define the enum as: