skip to content

In a Rails 8.1 Order model, what does enum :status, { placed: 0, baking: 1, out_for_delivery: 2, delivered: 3 } give you?

level: juniorimportance: must knowfreq 64%

answer

  1. the column keeps the integer
  2. reader returns the label string
  3. baking? and baking!
  4. Order.baking and Order.not_baking
  5. Order.statuses maps labels to values

basics

~20 s

An integer status column read and written by name: order.status returns "baking", baking? and baking! check and save a value, Order.baking and Order.not_baking are scopes, and Order.statuses holds the label-to-integer map. Unknown values raise ArgumentError.

solid answer

~40 s

The `status` column still holds integers, but Active Record maps them to labels. `order.status` returns the label as a string, `"baking"`, and the writer accepts `"baking"`, `:baking` or `1`. For each label you get a predicate, `order.baking?`, and a bang method, `order.baking!`, which calls `update!(status: :baking)` and so saves immediately. You also get scopes, `Order.baking` and `Order.not_baking`, and `where(status: :out_for_delivery)` translates the label to its integer. `Order.statuses` returns the mapping, which you need for raw SQL fragments. Assigning a label that is not in the map, such as `:burnt`, raises `ArgumentError` at assignment time. In Rails 8.1 the name is a positional argument; the old keyword form, `enum status: {...}`, was removed in 8.0.

code

ruby · 12 lines
ruby
class Order < ApplicationRecord
  enum :status, { placed: 0, baking: 1, out_for_delivery: 2, delivered: 3 }
end

order = Order.create!(status: :placed)
order.status            # => "placed"
order.baking!           # saves status = 1 with update!
order.baking?           # => true
Order.out_for_delivery  # WHERE status = 2
Order.not_delivered     # WHERE status != 3
Order.statuses[:baking] # => 1
order.status = :burnt   # ArgumentError: 'burnt' is not a valid status

go deeper

for a junior

Recall the generated pieces: string reader, predicates, bang methods that save, scopes and their not_ versions, and the pluralised mapping method.

for a middle

Explain how labels translate to stored integers in hash conditions but not in raw SQL, and why an unknown label raises at assignment.

for a senior

Watch for the production traps: bang methods that save mid-request, symbol comparisons that always fail, and label clashes that only show up at class load.

for a principal

Decide where state lives: a simple enum suits a closed list, while states with rules and history may need their own model or table.

## What enum is for An **enum** in Active Record turns a column that holds a small set of codes into named states. A pizza `Order` moves through `placed`, `baking`, `out_for_delivery` and `delivered`; storing small integers keeps the column compact and indexes cheap, while the model lets code talk in labels. The declaration is one line: `enum :status, { placed: 0, baking: 1, out_for_delivery: 2, delivered: 3 }`. The attribute must be backed by a database column, or declared with an explicit type through the Attributes API; otherwise Rails raises once the model's attribute types are loaded, with a message about an undeclared attribute type for the enum. ## What the declaration generates | Generated | Example | What it does | |---|---|---| | Reader | `order.status` | returns the label as a string, `"baking"` | | Writer | `order.status = :baking` | accepts a label string, a symbol or the mapped integer | | Predicate | `order.baking?` | compares the stored value with the label's value | | Bang method | `order.baking!` | runs `update!(status: :baking)`, saving at once | | Scope | `Order.baking` | `where(status: 1)` | | Negative scope | `Order.not_baking` | `where.not(status: 1)` | | Mapping | `Order.statuses` | `{"placed" => 0, "baking" => 1, ...}` with indifferent access | ## Querying - **Hash conditions translate labels**: `Order.where(status: :delivered)` and `Order.where(status: [:placed, :baking])` send the integers. - **Raw SQL does not**: inside a string fragment you pass the value yourself, `Order.where("status <> ?", Order.statuses[:delivered])`. - **The generated scopes** are ordinary scopes, so they chain: `Order.baking.where(store_id: 3)`. ## Assignment rules 1. A known label, as a string or a symbol, is stored as its integer. 2. The integer itself is accepted too, so `order.status = 1` reads back as `"baking"`. 3. `nil` is allowed unless a validation forbids it. 4. Anything else raises `ArgumentError` with a message such as `'burnt' is not a valid status`, at the moment of assignment, which in a controller means an exception rather than a validation error. A `validate:` option changes that. ## Pitfalls interviewers probe - **`baking!` saves.** It is not a setter; it writes to the database with `update!`, runs validations and callbacks, and raises `ActiveRecord::RecordInvalid` if the record is invalid. - **Comparing with symbols fails.** `order.status == :baking` is `false`, because the reader returns a string; use `order.baking?`. - **Name clashes are checked.** A label that would generate a method Active Record already defines, or that another enum on the model already generated, raises `ArgumentError` when the class loads. - **The keyword form is gone.** Rails 8.0 removed `enum status: { ... }`; Rails 8.1 code passes the name first. ## Reading the generated code The generated methods live in a module that `enum` includes into the model, not in the class body. Two consequences: 1. You can override one and call `super`, for example to log every `delivered!` before it saves. 2. The predicates compare the value as it will be written, `status_for_database == 1`, so they agree with the database even if the attribute was assigned as an integer. `Order.defined_enums` returns every enum on the model with its mapping, which is handy for generic admin screens. ## Using enums in forms and APIs - **Select boxes**: `Order.statuses.keys` gives the labels for a dropdown, and the submitted string assigns cleanly. - **JSON output**: `as_json` emits the label string, not the integer, because it reads through the attribute. - **Fixtures and factories**: both may use the label, `status: delivered` in a fixture file, and Rails maps it. - **Defaults**: a database default of `0` reads back as `"placed"`; the `default:` option can state it in the model instead. ## Where it sits Enums cover the common case of a closed set of states with cheap storage. Validation messages for them, native database enum types and converter theory are separate subjects; the core interview answer is the generated API above and the fact that the database holds the mapped value, not the label.

  • How do you use an enum value inside a raw SQL fragment?
    Look the integer up through the mapping method, because string fragments are passed through untouched: `Order.where("status <> ?", Order.statuses[:delivered])`. Hash conditions such as `where(status: :delivered)` do the translation for you, which is why they are preferred.
  • What happens when order.delivered! is called on an invalid order?
    The bang method is `update!(status: :delivered)`, so it runs validations and callbacks and raises `ActiveRecord::RecordInvalid` when the record is invalid; nothing is saved. Use the writer plus `save` when you want a `false` return instead of an exception.

  • The column stores the string 'baking' when the enum maps labels to integers
  • order.baking! only changes the attribute in memory
  • order.status returns the symbol :baking
  • Assigning an unknown status adds a validation error by default
  • Rails 8.1 still accepts the keyword form enum status: { placed: 0 }

Assumes Rails 8.1; enum takes the attribute name as a positional argument, because the keyword form enum status: {...} was removed in Rails 8.0.