skip to content

In a Rails 8.1 model, what happens when code changes an attr_readonly attribute such as order_number on a persisted record?

level: middleimportance: nice to knowfreq 16%

answer

  1. settable on create only
  2. raise_on_assign_to_attr_readonly
  3. ActiveRecord::ReadonlyAttributeError
  4. update_column raises too
  5. readonly! locks the whole record

basics

~20 s

With load_defaults 7.1 or later, assigning a new value to an attr_readonly attribute of a persisted record raises ActiveRecord::ReadonlyAttributeError. On older defaults the value changed in memory but was silently left out of the UPDATE.

solid answer

~40 s

`attr_readonly :order_number` lets a new `Order` set the number in its `INSERT` and then freezes that column for the record's life. With `load_defaults 7.1` or later, which includes every new Rails 8.1 app, `config.active_record.raise_on_assign_to_attr_readonly` is `true`, so `order.order_number = "X"` or `order.update(order_number: "X")` on a persisted record raises `ActiveRecord::ReadonlyAttributeError`. The framework default is `false`, which upgraded apps on older defaults still run: the assignment succeeds in memory and `save` quietly leaves the column out, a confusing silent no-op. `update_column`, `update_columns` and `touch` on that attribute raise `ActiveRecord::ActiveRecordError`. Class-level `update_all` writes SQL directly and is not checked. `readonly!` is different: it marks one loaded record so any save raises `ActiveRecord::ReadOnlyRecord`.

code

ruby · 11 lines
ruby
class Order < ApplicationRecord
  attr_readonly :order_number
  before_create { self.order_number ||= "PZ-#{SecureRandom.hex(4).upcase}" }
end

order = Order.create!(phone: "5558675309")
order.order_number = "PZ-0000"
# => raises ActiveRecord::ReadonlyAttributeError

order.readonly!
order.save # raises ActiveRecord::ReadOnlyRecord

go deeper

for a junior

Know that attr_readonly columns can be set on create but not changed afterwards, and that a new app raises an error when code tries.

for a middle

Explain the raise_on_assign_to_attr_readonly flag, its framework default false, and how update_column and update_all treat readonly attributes.

for a senior

Check the flag during upgrades, find code that depended on the silent ignore, and add database protection where the guarantee really matters.

for a principal

Decide which identifiers are immutable by contract and enforce that at the database layer, using attr_readonly as an early warning rather than the guarantee.

## What attr_readonly protects Some columns must never change after the row exists: an order number printed on a receipt, an external reference sent to a payment provider, a slug in shared links. `attr_readonly :order_number` tells Active Record that the attribute is **writable on create only**. `Order.readonly_attributes` returns the list for the class. ## Behaviour on a persisted record | Action on a persisted order | With load_defaults 7.1+ | With older defaults | |---|---|---| | `order.order_number = "X"` | raises `ActiveRecord::ReadonlyAttributeError` | changes memory only | | `order.update(order_number: "X")` | raises `ActiveRecord::ReadonlyAttributeError` | returns true, column not written | | `order.update_column(:order_number, "X")` | raises `ActiveRecord::ActiveRecordError` | raises `ActiveRecord::ActiveRecordError` | | `order.touch(:order_number)` | raises `ActiveRecord::ActiveRecordError` | raises `ActiveRecord::ActiveRecordError` | | `Order.where(id: order.id).update_all(order_number: "X")` | writes the row | writes the row | The switch is `config.active_record.raise_on_assign_to_attr_readonly`. The framework default is `false`; `load_defaults 7.1` sets it to `true`, and a new Rails 8.1 app inherits that. ## Why the raising behaviour is better The old behaviour was a silent no-op: 1. A support tool lets staff correct an order number. 2. The form submits, `update` returns `true`, the page shows the new number from memory. 3. On reload the old number is back, and nobody saw an error. Raising turns that into an immediate, visible failure in development and in tests. ## attr_readonly versus readonly! - **`attr_readonly`** is declared on the class and protects specific columns of every record after creation. - **`readonly!`** is called on one loaded object and blocks saving it at all: `save` raises `ActiveRecord::ReadOnlyRecord`. Records loaded with the `readonly` query method, `Order.readonly.first`, behave the same way. - Neither is a database guarantee. `update_all`, raw SQL, other services and console sessions can still change the column; a database trigger or column privileges are the only hard stop. ## Where the check lives With the flag on, Active Record includes a small module that checks the attribute name on every write to an attribute of a persisted record and raises `ReadonlyAttributeError` before the value changes. A new record skips the check, which is why the value can be set at creation, including from a `before_create` callback. `update_column` and `touch` run their own check and raise the generic `ActiveRecordError` with an "is marked as readonly" message, whichever way the flag is set. ## Testing it A single test documents the intent: create an order, assert that assigning a new `order_number` raises `ActiveRecord::ReadonlyAttributeError`, and assert that a newly built order can still set one. That test also fails loudly if someone later turns the flag off for the whole app. ## Practical guidance - Assign the value in `before_create` or from a generator so nothing else ever sets it. - Keep `attr_readonly` columns out of permitted parameters for update actions, so a request cannot even attempt the assignment. - When upgrading an older app, flip `raise_on_assign_to_attr_readonly` deliberately and watch for code that relied on the silent ignore, such as a form that resubmits every field. ## Interview angle This is a niche macro, so interviewers mostly use it to check whether you know that defaults moved with `load_defaults`. The strong answer names the exception, the configuration flag and its framework default, and contrasts `attr_readonly` with `readonly!`. Mentioning that `update_all` bypasses the protection shows you understand it is a model-level guard, not a data guarantee.

  • Does attr_readonly stop Order.update_all(order_number: nil)?
    No. `update_all` builds one SQL `UPDATE` for the relation without instantiating records, so model-level checks, readonly attributes included, never run. Only database-level protection, such as a trigger or column privileges, stops it.

  • attr_readonly prevents setting the column when the record is created
  • With 7.1 defaults the change is silently ignored on save
  • update_all respects attr_readonly because it goes through the model
  • attr_readonly and readonly! are two names for the same protection

Assumes Rails 8.1 with load_defaults 7.1 or later, which sets raise_on_assign_to_attr_readonly to true; the framework default false silently ignores the change on save.