Enum Pitfalls and How to Avoid Them

1. Forgetting to Use Integer Columns

Enums only work with integer columns. Using a string column will cause errors:

class AddStatusToUsers < ActiveRecord::Migration[8.0]
  def change
    add_column :users, :status, :string, default: "active"  # Incorrect!
  end
end

Fix: Always use integer for enum columns.

2. Renaming Enum Keys Without Migration

Renaming an enum key without updating stored values can cause inconsistent data:

#Before
enum :status, { active: 0, inactive: 1, banned: 2 }

#After (Problematic Change)
enum :status, { enabled: 0, disabled: 1, banned: 2 }

Fix: Instead of renaming, add a new enum and migrate existing records.

3. Overlapping Integer Values

Avoid using duplicate integers for different enums within the same model:

enum :role, { admin: 0, user: 1 }
enum :status, { active: 0, inactive: 1 }  # Conflicting 0 and 1 values

Fix: Ensure unique integer mappings across enums in the same model.