In a Rails 8.1 app on PostgreSQL, when would you use create_enum and t.enum for a sneaker's condition, and what does it cost later?
answer
- create_enum name, values
- t.enum :condition, enum_type:
- schema.rb dumps create_enum
- add_enum_value is irreversible in change
- attribute is a plain String
basics
~20 screate_enum defines a PostgreSQL enum type and t.enum ... enum_type: uses it, so the database rejects any other value. Adding values later takes add_enum_value, which cannot be reverted in change, and removing a value means rebuilding the type.
solid answer
~40 s`create_enum :sneaker_condition, ["deadstock", "used", "worn"]` creates the type, and `t.enum :condition, enum_type: :sneaker_condition, default: "used", null: false` gives a column the database itself restricts; `db/schema.rb` dumps the `create_enum` line too. Active Record reads the column as a plain `String`; pair it with the model's `enum` macro, mapping names to the same strings, for predicates and scopes. An invalid value fails in PostgreSQL with `ActiveRecord::StatementInvalid`, not a validation error. The cost is change: `add_enum_value :sneaker_condition, "refurbished", after: "used"` is irreversible inside `change` (Rails raises `IrreversibleMigration` on rollback), `rename_enum_value` needs `from:` and `to:`, and dropping a value has no command at all. Choose it for small, stable sets several apps write to; prefer a string column with a check constraint for sets that will grow.
go deeper
Recall create_enum to define the type and t.enum with enum_type: to use it, with the attribute read as a String.
Explain the schema.rb dump, why invalid values raise StatementInvalid, and how add_enum_value and rename_enum_value reverse or not.
Choose between a native type, a check constraint and an integer enum on stability, readers and migration cost.
Set a schema policy for constrained values across services, weighing enforcement in the database against change speed.
## What the migration methods do The PostgreSQL adapter adds a family of migration methods for **enum types**, a named list of allowed string values that columns can use: ```ruby class AddConditionToSneakers < ActiveRecord::Migration[8.1] def change create_enum :sneaker_condition, ["deadstock", "used", "worn"] add_column :sneakers, :condition, :enum, enum_type: :sneaker_condition, default: "used", null: false end end ``` Inside `create_table` the column is `t.enum :condition, enum_type: :sneaker_condition`. `create_enum` wraps `CREATE TYPE ... AS ENUM` in a check, so it does nothing if the type already exists. The schema dump writes the type before the tables (`create_enum "sneaker_condition", ["deadstock", "used", "worn"]`) and the column with `enum_type: "sneaker_condition"`, so `db:schema:load` rebuilds both. ## How Active Record sees the column - The attribute is a plain **String**: `sneaker.condition # => "used"`. The adapter's enum type casts any value with `to_s`. - Assigning `"mint"` raises nothing in Ruby; the `INSERT` fails in PostgreSQL, and Rails wraps the driver's invalid-input error in `ActiveRecord::StatementInvalid`. Users get an error page, not a form message. - For predicates, scopes and validation, combine it with the model's `enum` macro, mapping each name to the database string. How that macro behaves is its own topic; the database type and the macro are independent layers. ## The change-management cost | Change | Rails method | Catch | |---|---|---| | add a value | `add_enum_value :sneaker_condition, "refurbished", after: "used"` | not reversible inside `change` | | rename a value | `rename_enum_value :sneaker_condition, from: "worn", to: "beaters"` | needs both `from:` and `to:` to reverse | | rename the type | `rename_enum :sneaker_condition, :listing_condition` | reversible | | drop the type | `drop_enum :sneaker_condition, [...]` | reversible only if you pass the values | | remove one value | none | rebuild the type and convert the column | `add_enum_value` is not on the command recorder's list of invertible commands, so rolling back a `change` migration that uses it raises `ActiveRecord::IrreversibleMigration`. Write it with `up` and an explicit `down` that explains why the value stays, or accept a forward-only migration. PostgreSQL also restricts using a freshly added value in the same transaction that added it, which matters because Rails runs each migration in a transaction; the rules are PostgreSQL's. ## Rolling out a new value Because the old and new versions of the app run side by side for a few minutes during a deploy, add values in two steps: 1. Ship the migration with `add_enum_value` first, with no code that writes the new value yet. 2. Ship the code that writes `"refurbished"` in a later release, once every running process tolerates reading it. 3. To retire a value, stop writing it, convert existing rows to another value, and only then rebuild the type, usually by creating a new type and switching the column to it. ## Choosing between the options | Option | Enforced by | Adding a value | Good fit | |---|---|---|---| | PostgreSQL enum type | the database type | `add_enum_value`, forward-only | small, stable sets; several apps writing | | string column + check constraint | a `CHECK` you can drop and re-add | replace the constraint | sets that grow; readable data | | integer column + `enum` macro | Ruby only | edit the model | single-app data, compact storage | For the marketplace, the condition grades are fixed by the business and rarely change, other services read the table directly, and reports read `"deadstock"` more easily than `0`. That favours the native type. A `shipping_carrier` list that grows every quarter would be a string with a check constraint instead. ## What interviewers listen for - knowing that the database type and the Rails `enum` macro are separate, and what each enforces; - knowing that invalid values surface as `StatementInvalid`, so a model validation is still worth having for form errors; - knowing that adding values is forward-only and removing one is a rebuild; - choosing the type on stability, not on habit.
- Why does rolling back a change migration that calls add_enum_value raise in Rails 8.1?The migration command recorder has no inverse for `add_enum_value`, because PostgreSQL has no command to remove one enum value. When Rails tries to invert the `change` method it raises `ActiveRecord::IrreversibleMigration`. Use `up` and `down`, and decide explicitly what `down` does.
- What happens when a form submits condition: "mint" for a column backed by a PostgreSQL enum type and the model has no validation?Active Record casts it to the string "mint" and sends the INSERT; PostgreSQL rejects it as an invalid enum input, and Rails raises `ActiveRecord::StatementInvalid`. The user sees an error page instead of a form message, so add an inclusion validation or use the `enum` macro's validation option.
- Thinks t.enum alone gives Rails predicate methods like used?
- Expects an invalid enum value to add a validation error
- Writes add_enum_value inside change and assumes rollback works
- Expects drop_enum to remove a single value from the type
- Picks a native enum for a list that changes every few weeks