skip to content

In a Rails 8.1 model, how do enum declarations with an array, an integer hash and a string hash differ, and which fits?

level: middleimportance: must knowfreq 50%

answer

  1. array maps by position
  2. append only, never reorder
  3. hash pins each value
  4. string values are readable in SQL
  5. convert array to matching hash

basics

~20 s

An array maps labels to integers by position, so inserting or removing a label silently remaps stored rows. An integer hash pins each value, and a string hash stores the label text. Prefer a hash; use strings when people read the table.

solid answer

~40 s

`enum :status, [:placed, :baking, :delivered]` stores `0`, `1` and `2` by array position. That is fine until someone inserts `:cancelled` before `:delivered` or deletes `:baking`: no data changes, but every stored `2` now reads as the new label, silently. The explicit hash, `{ placed: 0, baking: 1, delivered: 2 }`, pins each label to its value, so you can add a label anywhere, retire one by removing it, and reorder freely. A string hash, `{ placed: "placed", baking: "baking" }`, stores the label text in a string column: SQL consoles and reports read clearly and reordering cannot hurt, at the cost of a wider column and, as the Rails docs warn, likely slower queries. To convert an existing array enum, write the hash with the current positions; no migration is needed.

code

ruby · 8 lines
ruby
# Risky: values come from positions 0, 1, 2
enum :status, [:placed, :baking, :delivered]

# Same data, pinned explicitly; safe to extend anywhere
enum :status, { placed: 0, baking: 1, delivered: 2, cancelled: 3 }

# Label text stored in a string column
enum :status, { placed: "placed", baking: "baking", delivered: "delivered" }

go deeper

for a junior

Remember that an array enum stores positions, so new labels go at the end, and that a hash pins each value explicitly.

for a middle

Explain the silent remapping when an array label is inserted or removed, and how to convert to an equivalent hash without touching data.

for a senior

Choose between integer and string mappings by who reads the table, and plan label retirement so old values never take on a new meaning.

for a principal

Treat enum values as a data contract shared with reports, warehouses and other services; changing them needs the same care as a schema change.

## Three ways to declare the mapping Rails 8.1 accepts the values of an enum as an **array** or a **hash**, and a hash can map labels to integers or to strings. | Declaration | Stored in the column | Safe to reorder or remove labels? | Column type | |---|---|---|---| | `enum :status, [:placed, :baking, :delivered]` | `0`, `1`, `2` by position | no | integer | | `enum :status, { placed: 0, baking: 1, delivered: 2 }` | the integers you wrote | yes | integer | | `enum :status, { placed: "placed", baking: "baking" }` | the strings you wrote | yes | string | An array must hold only symbols or only strings, and `%w[placed baking]` is still an array: it maps by position to integers exactly like the symbol version. Hash values may be integers, strings, floats, booleans or `nil`; symbols are converted to strings. ## Why the array form is risky With an array, the i-th label is stored as `i - 1`. The Rails documentation spells out the consequence: once values are in use, new labels may only be appended and existing ones never moved or deleted. The failure is silent: 1. The `Order` enum is `[:placed, :baking, :delivered]`, and thousands of rows store `2` for delivered. 2. A developer adds `:cancelled` between `:baking` and `:delivered` because it reads better. 3. After deploy, every delivered order reads as `"cancelled"`, and `Order.delivered` now looks for `3`, which no old row holds. 4. No error, no failing migration; only wrong data in reports and customer emails. Removing a label is just as dangerous, because every later label shifts down by one. ## The explicit integer hash `{ placed: 0, baking: 1, out_for_delivery: 2, delivered: 3, cancelled: 4 }` decouples order from value: - add `cancelled: 4` anywhere in the list, - retire `baking` by deleting its pair, leaving `1` unused, after migrating any rows that still hold it, - read the declaration and know exactly what is in the database. Converting an existing array enum costs nothing: write the hash with the positions the array implied. The stored data already matches. ## String-backed enums `enum :status, { placed: "placed", baking: "baking", out_for_delivery: "out_for_delivery", delivered: "delivered" }` on a string column stores the label text: - **For**: anyone querying the database, a data warehouse or a support tool, sees meaningful values, and positions never matter. - **Against**: wider rows and indexes, and the Rails docs note it will likely make queries slower; renaming a label now means migrating data. Native database enum types are another option on some databases, with their own migration commands, and belong to database-specific configuration. ## Choosing in practice - New enum, application-only consumers: an explicit integer hash. - Values read by people or other systems straight from the table: a string hash. - Existing array enum: convert to the matching hash before the next change to its labels. - Never: an array whose labels will change. ## Adding a label during a rolling deploy Even with an explicit hash, a new label has a deploy-window edge. When the new code writes `cancelled: 4`, application processes still running the old code read that row with a mapping that has no `4`, and the reader returns `nil` instead of raising. Ship the label in the model first, and start writing it only once every process knows it; the same applies to background workers that load orders. ## Checking what is stored When in doubt, look at the data rather than the declaration: - `Order.statuses` shows the mapping Rails is using right now. - `order.status_before_type_cast` and a raw `SELECT status FROM orders` show the stored values. - Comparing `Order.group(:status).count` before and after a deploy that touches the enum is a cheap smoke test for silent remapping. ## Version note Rails 8.0 removed the keyword form `enum status: [...]` and `enum status: {...}`. Code on Rails 8.1 passes the attribute name first, `enum :status, ...`; when you meet the keyword form in an old codebase, it has to be rewritten during the upgrade.

  • How do you retire a label from an integer-hash enum safely?
    First migrate the rows that still hold its value to another state, then delete the pair from the hash and leave the number unused. Do not reuse the number for a new label later, or any old rows, fixtures or archived data holding it will silently take the new meaning.
  • Does enum :status, %w[placed baking] store strings because the labels are strings?
    No. Any array maps by position, whatever the label type, so `%w[placed baking]` stores `0` and `1`. Only a hash whose values are strings, `{ placed: "placed", baking: "baking" }`, stores text.

Numbering pizzas on a menu by their position works until a new pizza is printed in the middle: every regular who orders number 7 now gets something else. Printing a fixed number next to each pizza, the explicit hash, lets the menu change without changing anyone's order.

  • Inserting a label into an array enum makes Rails rewrite the stored numbers to match
  • An array of strings stores the strings in the column
  • Switching an array enum to a hash requires a data migration
  • A string-backed enum is as compact and fast as an integer one
  • Array enums are safe to reorder as long as the label names stay the same

Assumes Rails 8.1; the positional enum :status, ... form is the only one since the keyword form was removed in Rails 8.0.