Enum Pitfalls and How to Avoid Them

1. Confusion to Use Integer or String Columns

Enums can work with both integer and string columns. Using a string column will NOT cause any errors, however, using one over the other might provide both advantages or disadvantages of their own.

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

For further reading: Integer Enums vs. String Enums in Rails: Which One Should You Use?.


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.