skip to content

In Rails nested attributes, how do the id and _destroy keys decide whether a child record is created, updated or deleted?

level: middleimportance: should knowfreq 42%

answer

  1. no id builds, matching id updates
  2. _destroy needs allow_destroy: true
  3. boolean cast: "1" yes, "0" no
  4. marked, then deleted on parent save
  5. left-out children stay put

basics

~20 s

A hash without id builds a child and one with an id updates that child. With allow_destroy: true, a truthy _destroy marks it for deletion on the parent's save; without it, _destroy is ignored. Children left out are untouched.

solid answer

~40 s

Each hash in `questions_attributes` is routed by two control keys. No `id`: a new question is built. An `id` matching one of the survey's questions: that question gets the other values. An unknown id raises `ActiveRecord::RecordNotFound`. `_destroy` only counts when the macro says `allow_destroy: true`, which defaults to false. Then `{ id: 7, _destroy: "1" }` marks question 7 with `mark_for_destruction`, and it is deleted, callbacks and all, when the survey saves, inside the same transaction; a new hash flagged `_destroy` is simply not built. Without `allow_destroy`, the flag is ignored: the question is updated, never deleted. The flag is cast like a boolean column, so `"1"` and `"true"` delete while `"0"`, `"false"` and `""` do not. Questions missing from the payload are left alone.

code

ruby · 12 lines
ruby
class Survey < ApplicationRecord
  has_many :questions, dependent: :destroy
  accepts_nested_attributes_for :questions, allow_destroy: true
end

survey.update(questions_attributes: [
  { id: 7, prompt: "How large is your team?" },  # updates question 7
  { id: 8, _destroy: "1" },                       # marked, destroyed on save
  { prompt: "Preferred tools?" },                 # builds a new question
  { prompt: "", _destroy: "1" }                   # skipped: nothing built
])
# question 9, absent from the payload, is untouched

go deeper

for a junior

Recall the rules: no id creates, an id updates, and _destroy deletes only when allow_destroy: true is set.

for a middle

Explain marking versus deleting, how the flag is cast from form values, and why a new hash flagged _destroy is built when allow_destroy is off.

for a senior

Show you avoid the production traps: absent children are never removed, counts must ignore marked records, and deletes run callbacks inside the parent's transaction.

for a principal

Decide whether a client should send diffs with ids and _destroy flags or a full replacement handled by a form object, and what that means for concurrency.

## Two control keys Every hash handed to a nested writer such as `questions_attributes=` may carry two keys that are never assigned as attributes: **`id`**, which picks an existing child, and **`_destroy`**, which asks for that child to be removed. Their combination, together with the macro's `allow_destroy:` option, decides what happens to each hash. `allow_destroy:` defaults to `false`. ## The routing table | Hash in `questions_attributes` | `allow_destroy: false` (default) | `allow_destroy: true` | |---|---|---| | `{ prompt: "Role?" }` | builds a new question | builds a new question | | `{ prompt: "", _destroy: "1" }` | builds a new question anyway | skipped, nothing built | | `{ id: 7, prompt: "Team?" }` | updates question 7 | updates question 7 | | `{ id: 7, _destroy: "1" }` | updates question 7, flag ignored | marks question 7 for destruction | | `{ id: 999 }` (not this survey's) | raises `ActiveRecord::RecordNotFound` | raises `ActiveRecord::RecordNotFound` | The second row surprises people: without `allow_destroy`, a template row the user "removed" in the browser still turns into a record unless something else, such as `reject_if:`, filters it. ## How the flag is read `_destroy` is cast the way a boolean column is cast: - `true`, `"1"`, `"true"` and other non-false values count as truthy. - `false`, `0`, `"0"`, `"f"`, `"false"` and `"off"` count as false. - An empty string casts to `nil`, so it does not delete either. That is why a form checkbox, which sends `"0"` unchecked and `"1"` checked, maps cleanly onto the key. Models also gain a `_destroy` reader, returning `marked_for_destruction?`, so a form can render the checkbox's current state. ## When the delete happens Marking is not deleting. `{ id: 7, _destroy: "1" }` calls `mark_for_destruction` on question 7 and leaves it in `survey.questions` for now. The row is only removed when the survey is saved: 1. Validation skips children marked for destruction, so a doomed invalid question cannot block the save. 2. The survey's save destroys the marked question with `destroy`, so its own callbacks and `dependent:` cascades, such as deleting its choices, run. 3. Everything happens inside the survey's transaction; if a later step fails, the question survives. If the survey is never saved, nothing is deleted. ## A worked update For the update in the code example below, with `allow_destroy: true` and `dependent: :destroy` on `Question`'s choices, the survey's save produces this sequence inside one transaction: 1. The survey's own columns are updated if they changed. 2. Question 8, marked for destruction, is destroyed first: its choices go through their `dependent:` rule, then the question row is deleted. 3. Question 7 is updated with its new prompt, without being validated a second time. 4. The new question "Preferred tools?" is inserted with `survey_id` set. 5. The commit makes all of it visible at once; any exception rolls all of it back. ## Not a sync Nested attributes act only on the hashes they receive. A question that is absent from `questions_attributes` is neither updated nor deleted, so to remove a question the payload must name it with its `id` and a truthy `_destroy`. Code that expects "send the full list and Rails will drop the rest" leaves stale rows behind. ## Traps - **`reject_if:` does not block a delete.** A hash with a truthy `_destroy` and `allow_destroy: true` bypasses the `reject_if:` check. - **Counting children.** Marked questions are still in the collection until the save, so a rule like "at least one question" must ignore records whose `marked_for_destruction?` is true. - **Foreign ids fail loudly.** The lookup is scoped to the survey's own questions, so a tampered id raises instead of touching another survey.

  • Why might a question flagged _destroy: "1" still be updated rather than deleted?
    Because `allow_destroy:` defaults to false. Without it the writer ignores `_destroy`, assigns the hash's other values to question 7 and saves it. Add `allow_destroy: true` to the `accepts_nested_attributes_for` call to make the flag delete.
  • How do you replace a survey's whole question list through nested attributes?
    Send every question to keep with its `id`, every question to drop with its `id` and `_destroy: "1"`, and new ones without an `id`. Nested attributes never infer deletions from absence, so the client or a form object has to list the removals.

Like amending an order form: a line with no reference number adds an item, a line quoting a reference changes that item, and a struck-through line removes it only if the form type allows removals. Nothing changes until the whole amendment is filed.

  • Sending _destroy: "1" deletes the child even without allow_destroy.
  • The child row is deleted the moment the attributes are assigned.
  • Leaving a question out of questions_attributes deletes it on save.
  • _destroy: "0" also marks the child, since the key is present.
  • Marked children are deleted with delete, skipping their callbacks.