Indexing Enum Columns in Rails 8

In Rails 8, enum definitions are stricter, and new best practices for indexing have emerged.

Key Changes in Rails 8 Enum Handling

With these changes, you must ensure indexing is correctly applied to enum columns using the new syntax:

class User < ApplicationRecord
  enum :status, { active: 0, inactive: 1, banned: 2 }, validate: true

  # New Rails 8 syntax requires explicit naming for methods
  enum :role, { admin: 0, editor: 1, viewer: 2 }, prefix: "user_role"
end

Querying with indexes remains unchanged:

User.where(status: :active)
User.where(user_role: :admin)

However, defining indexes in migrations now aligns with the stricter syntax:

class AddIndexToUsersRails8 < ActiveRecord::Migration[8.0]
  def change
    add_index :users, :status, name: "index_users_on_status"
  end
end