Enforcing Enum Constraints at the Database Level

Using CHECK Constraints

To ensure only valid enum values exist in the database, use a CHECK constraint in PostgreSQL or MySQL.

class AddCheckConstraintToUsers < ActiveRecord::Migration[7.0]
  def change
    execute <<-SQL
      ALTER TABLE users ADD CONSTRAINT check_status_enum CHECK (status IN (0, 1, 2));
    SQL
  end
end

If someone tries to insert an invalid status, the database will reject it.