skip to content

In Rails nested attributes on a has_one, what happens to the existing record when the attributes lack an id, and what does update_only: true change?

level: seniorimportance: nice to knowfreq 18%

answer

  1. one-to-one writer takes a single hash
  2. no id builds a replacement
  3. old record handled by dependent:
  4. happens at assignment, not at save
  5. update_only: edits in place

basics

~20 s

Without an id, a has_one's nested writer builds a replacement and immediately detaches or destroys the existing record according to the association's dependent option. update_only: true makes the writer update the existing record in place, id or not.

solid answer

~40 s

Take `Survey has_one :schedule` with `accepts_nested_attributes_for :schedule`. `schedule_attributes = { closes_at: t }` without the current schedule's `id` does not edit it: the writer calls `build_schedule`, and building a has_one replacement removes the old record at once. With `dependent: :destroy` the old schedule is destroyed, with `:delete` it is deleted, and otherwise its `survey_id` is set to NULL and saved, all before the survey's own save. A mismatched `id` raises `ActiveRecord::RecordNotFound`. With `update_only: true`, the writer assigns to the existing schedule whether or not an `id` is sent, and builds one only when none exists. Inside `update`, the assignment runs in the same transaction as the save, so a failed save rolls the removal back; a bare assignment followed by `save` gets no such protection. `update_only:` is ignored for collections.

code

ruby · 11 lines
ruby
class Survey < ApplicationRecord
  has_one :schedule, dependent: :destroy
  accepts_nested_attributes_for :schedule, update_only: true
end

survey.schedule.id   # => 5
survey.update(schedule_attributes: { closes_at: 2.weeks.from_now })
survey.schedule.id   # => 5, edited in place

# Without update_only: true the same call would build a new schedule
# and destroy schedule 5 during the assignment.

go deeper

for a junior

Recall that a has_one nested hash without an id builds a new record, and update_only: true makes it edit the existing one instead.

for a middle

Explain the decision table for one-to-one writers, how dependent: decides the old record's fate, and why update_only is ignored on collections.

for a senior

Spot the timing trap: replacement removes the old row at assignment, so only a surrounding transaction, as update provides, protects it from a failed save.

for a principal

Decide whether a one-to-one child is an editable extension or a replaceable version, and encode that choice in update_only and dependent: deliberately.

## The one-to-one writer `accepts_nested_attributes_for` also works on one-to-one associations, `has_one` and `belongs_to`. The generated writer, such as `schedule_attributes=`, takes a single hash instead of a list. In a survey builder, a `Survey` might `has_one :schedule` holding `opens_at` and `closes_at`, edited on the same form as the survey's title. The writer's decision for a one-to-one link turns on whether the hash identifies the current record: | Hash | Existing schedule? | `update_only: false` (default) | `update_only: true` | |---|---|---|---| | `{ closes_at: t }` | none | builds a schedule | builds a schedule | | `{ closes_at: t }` | yes | builds a replacement | updates the existing one | | `{ id: 5, closes_at: t }`, id matches | yes | updates schedule 5 | updates schedule 5 | | `{ id: 9, closes_at: t }`, id differs | yes | raises `ActiveRecord::RecordNotFound` | updates the existing one | ## What a replacement does, and when Without `update_only`, a hash with no `id` makes the writer call `build_schedule`. Building a new target for a `has_one` that already has one replaces it, and the replacement acts **immediately**, during assignment: 1. With `dependent: :destroy`, the old schedule is destroyed right away, running its callbacks. 2. With `dependent: :delete`, it is deleted with a single statement. 3. Otherwise its foreign key is set to `NULL` and the old row is saved, provided the survey is persisted; a `NOT NULL` constraint on `survey_id` turns that into a database error. The new schedule itself is only saved later, with the survey. That ordering is the trap: if the survey then fails validation, the old schedule may already be gone. - **`survey.update(schedule_attributes: ...)`** assigns inside the transaction that wraps the save, so a failed save rolls the removal back. - **`survey.schedule_attributes = ...` followed by `survey.save`** performs the removal outside any transaction the save opens, so it sticks even when the save fails. ## What update_only: true changes `update_only: true` tells the writer that the one-to-one record is edited, never swapped: - If a schedule exists, the hash's attributes are assigned to it, whatever `id` the hash carries or lacks. - If no schedule exists, one is built. - Combined with `allow_destroy: true`, a truthy `_destroy` marks the existing schedule for destruction even without an `id`. - On a collection association the option is ignored. ## How update_only changes the timing trap With `update_only: true`, an existing schedule is never replaced, so the immediate removal described above cannot happen through this writer: the assignment only changes attributes in memory, and they are written when the survey saves. The only remaining way for the old row to go is an explicit `_destroy`, and that is a mark, applied when the survey saves inside its transaction. This makes `update_only: true` the safer default for one-to-one children that a form edits in place. ## When to use which - Use **`update_only: true`** when the child is a settings-like extension of the parent, such as a schedule, a profile or a preferences row, and the form never intends to swap it for a new row. - Keep the **default** when replacement is meaningful and the old record must survive as history, typically with no `dependent:` so it is detached rather than destroyed. - Either way, send the `id` from the form when editing an existing record; it makes the intent explicit and the default behaviour harmless. ## Other one-to-one details - A hand-built child is respected: if the reader already returns a new, unsaved schedule, the writer assigns to it instead of building another. - A polymorphic `belongs_to` cannot be built from attributes alone, so its nested writer raises `ArgumentError` unless the model provides a builder.

  • Why can the old schedule disappear even though survey.save returned false?
    Replacing a has_one target removes the old record during assignment, before validation. If the code assigned `schedule_attributes=` and then called `save`, that removal ran outside the save's transaction and is not rolled back. Using `update`, which wraps assignment and save in one transaction, or `update_only: true` avoids it.
  • Does update_only: do anything on has_many :questions?
    No. The option is documented for one-to-one associations and the collection writer never reads it; collections always match existing children by `id` and build the rest.

  • A has_one hash without an id always updates the existing record.
  • The replaced has_one record is only removed when the parent saves.
  • update_only: true also makes has_many children update without ids.
  • A mismatched id on a has_one hash silently builds a new record.