skip to content

In a Rails 8.1 model, what do enum's prefix:, suffix:, scopes:, instance_methods: and validate: options change?

level: middleimportance: should knowfreq 34%

answer

  1. two enums sharing a label clash
  2. prefix: true gives status_baking?
  3. scopes: false drops class scopes
  4. validate: true instead of ArgumentError
  5. validate: { allow_nil: true }

basics

~20 s

prefix: and suffix: rename the generated predicates, bang methods and scopes so labels shared by two enums do not clash; scopes: false and instance_methods: false skip generating those; validate: true turns an unknown value into a validation error instead of ArgumentError.

solid answer

~40 s

Each label generates `label?`, `label!`, a `label` scope and a `not_label` scope. `prefix: true` puts the attribute name in front, `status_baking?` and `Order.status_baking`; `prefix: :kitchen` uses your word, `kitchen_baking?`; `suffix:` does the same at the end. You need them when two enums share a label, such as `paid` in both `status` and `payment_status`: without them Rails raises `ArgumentError` at class load because the second enum would redefine `paid?`. `scopes: false` skips the class scopes and `instance_methods: false` skips the predicates and bang methods. `validate: true`, added in Rails 7.1, stops the `ArgumentError` on assignment: the value is kept and `valid?` fails with an inclusion error, and `nil` fails too unless you pass `validate: { allow_nil: true }`. `default:` sets the initial label.

code

ruby · 12 lines
ruby
class Order < ApplicationRecord
  enum :status, { placed: 0, baking: 1, delivered: 2, paid: 3 }
  enum :payment_status, { pending: 0, paid: 1, refunded: 2 },
       prefix: :payment, validate: true, default: :pending
end

order = Order.new
order.payment_pending?             # => true
Order.payment_refunded             # scope
order.payment_status = :bounced
order.valid?                       # => false, inclusion error
order.paid?                        # status enum, not payment

go deeper

for a junior

Know that prefix: and suffix: rename the generated methods and that validate: true reports bad values as validation errors.

for a middle

Explain the load-time ArgumentError when two enums share a label, and which generated methods scopes: false and instance_methods: false remove.

for a senior

Choose validate: for user-facing input, rename methods before clashes reach production, and fix underscored options during upgrades.

for a principal

Agree team conventions for enum naming across models so state methods read consistently and adding a second state column never forces renames.

## The methods options act on For every label, `enum :status, { placed: 0, baking: 1, ... }` generates four things: an instance predicate (`baking?`), an instance bang method (`baking!`), a class scope (`Order.baking`) and a negative scope (`Order.not_baking`). The options either rename those methods or switch groups of them off. ## Renaming: prefix: and suffix: | Option | Predicate | Bang | Scope | |---|---|---|---| | none | `baking?` | `baking!` | `Order.baking` | | `prefix: true` | `status_baking?` | `status_baking!` | `Order.status_baking` | | `prefix: :kitchen` | `kitchen_baking?` | `kitchen_baking!` | `Order.kitchen_baking` | | `suffix: true` | `baking_status?` | `baking_status!` | `Order.baking_status` | The negative scopes follow suit: `Order.not_status_baking`. You reach for these for two reasons: - **Two enums share a label.** `enum :status, [:placed, :paid]` and `enum :payment_status, [:pending, :paid]` both want `paid?`. Rails detects the clash and raises `ArgumentError` when the class loads, naming the method another enum already defined. Prefixing one of them resolves it. - **Readability.** `order.payment_paid?` says more than `order.paid?` once a model has several state columns. Rails also raises at load time when a label would generate a method Active Record already uses, or a scope that clashes with a relation method; renaming or `scopes: false` is the escape hatch. ## Switching generation off: scopes: and instance_methods: - `scopes: false` skips the label and `not_` scopes, for example when the model already defines a scope of that name, or the labels would read badly as class methods. - `instance_methods: false` skips the predicates and bang methods, leaving only the attribute reader, writer and mapping method. Both default to `true`. The mapping method, `Order.statuses`, is always defined. ## validate: and default: By default an unknown label raises `ArgumentError` the moment it is assigned, which turns bad form input into an exception. With `validate: true`, available since Rails 7.1: 1. the assignment no longer raises; the value is held in memory, 2. `valid?` runs an inclusion validation against the labels and returns `false`, 3. `nil` is also rejected, unless you pass options through: `validate: { allow_nil: true }`. `default: :placed` sets the label a new record starts with; it is passed to the attribute definition under the hood. ## Old names that now fail Rails used to spell some options with a leading underscore. In Rails 8.1, `_prefix:`, `_suffix:`, `_scopes:`, `_default:` and `_instance_methods:` raise `ArgumentError` listing the valid options, so upgrading code must rename them. The same upgrade must also move away from the keyword form `enum status: ...`, removed in Rails 8.0. ## Inspecting the result - `Order.defined_enums` lists every enum with its label-to-value mapping. - `Order.statuses` (the pluralised attribute name) returns one mapping, whatever the prefix. - `Order.respond_to?(:payment_paid)` confirms which scope names were generated. ## What the options do not change - The **stored values** never change with `prefix:` or `suffix:`; only method names do, so renaming is safe for data but breaks callers of the old method names. - The **reader and writer** keep the attribute name: `order.payment_status` and `order.payment_status = :paid` whatever the prefix. - **Hash conditions** keep working with labels: `Order.where(payment_status: :paid)` is unaffected by `scopes: false`. - `validate:` adds a model validation only; it does not add a database constraint, so writes that skip validations, or SQL from elsewhere, are not checked by it. ## A worked declaration `enum :payment_status, { pending: 0, paid: 1, refunded: 2 }, prefix: :payment, validate: true, default: :pending` gives `payment_paid?`, `Order.payment_refunded`, a validation error rather than an exception for an unknown value from a form, and `pending` on new orders. Each option exists to solve one specific friction; an interviewer wants to hear which friction.

  • Why would you pick validate: true for an enum assigned from form input?
    Without it, an unexpected value from the request raises `ArgumentError` during assignment, which surfaces as a server error instead of a form message. With `validate: true` the record simply fails validation, `errors` explains why, and the controller can re-render the form.

  • Two enums can share a label because Rails namespaces them automatically
  • prefix: true changes the values stored in the database
  • validate: true still raises ArgumentError but also adds an error
  • scopes: false removes the Order.statuses mapping method
  • The _prefix: option still works as an alias in Rails 8.1

Assumes Rails 8.1: validate: arrived in Rails 7.1, the underscored option names raise ArgumentError, and the keyword form was removed in Rails 8.0.