Setting Up Enum in Rails 8 with Migrations
Before defining an enum, you need a database column to store the values. Since enums are internally stored as integers, your migration should specify the column as integer
.
Creating a Migration for Enums
For example, if we have a users table and want to add a status column with enums:
rails generate migration AddStatusToUsers status:integer
This generates a migration file like:
class AddStatusToUsers < ActiveRecord::Migration[8.0]
def change
add_column :users, :status, :integer, default: 0, null: false
end
end
default: 0
ensures new records have a valid default value.null: false
enforces data integrity, preventing NULL values in the column.
After defining the migration, run it:
rails db:migrate
Now the users
table has a status
column ready for enum usage.