In an Active Record Survey model, what does accepts_nested_attributes_for :questions add, and how does one save write the survey with its questions?
answer
- generated questions_attributes= writer
- autosave switched on for the association
- array, or hash of hashes
- no id builds, matching id updates
- one transaction on the parent's save
basics
~10 saccepts_nested_attributes_for :questions defines a questions_attributes= writer and turns on autosave, so nested hashes build or update questions in memory and one survey save writes everything in a single transaction.
solid answer
~40 sOn a `Survey` that `has_many :questions`, `accepts_nested_attributes_for :questions` generates `questions_attributes=` and sets autosave on the association. `Survey.create(title: "Onboarding", questions_attributes: [{ prompt: "Your role?" }, { prompt: "Team size?" }])` builds two unsaved questions in memory; the save then validates the survey and those questions, inserts the survey, and inserts each question with `survey_id` set, all inside the survey's transaction. A hash without `id` builds a new child; a hash with an `id` updates that child, and an id that is not one of this survey's questions raises `ActiveRecord::RecordNotFound`. Forms submit the collection as a hash keyed `"0"`, `"1"`, whose keys are ignored. `Question` can declare `accepts_nested_attributes_for :choices` too, so answer choices ride in the same payload.
code
ruby · 21 linesclass Survey < ApplicationRecord
has_many :questions, dependent: :destroy
accepts_nested_attributes_for :questions
end
class Question < ApplicationRecord
belongs_to :survey
has_many :choices, dependent: :destroy
accepts_nested_attributes_for :choices
end
survey = Survey.create!(
title: "Onboarding pulse",
questions_attributes: {
"0" => { prompt: "Your role?",
choices_attributes: [{ label: "Engineer" }, { label: "Designer" }] },
"1" => { prompt: "Team size?" }
}
)
survey.questions.count # => 2
survey.questions.first.choices.count # => 2go deeper
Recall the generated questions_attributes= writer, that hashes without id create children and hashes with id update them, and that one parent save writes it all.
Explain that the macro turns on autosave, how the hash-of-hashes form shape is read, and why foreign ids raise RecordNotFound.
Show you can run nested writes across three levels inside one transaction and know where they stop: no collection replacement, no updates on a new parent.
Judge when nested attributes keep a form simple and when a dedicated form object or service is clearer for a multi-model write.
## What the macro defines **Nested attributes** let one model accept attributes for its associated records and save the whole graph through the parent. They are off by default; `accepts_nested_attributes_for` switches them on per association. In a survey builder, a `Survey` has many `Question` records and each question has many `Choice` records, and the goal is one form, one request and one save. Calling `accepts_nested_attributes_for :questions` on `Survey` does three things: - It defines a writer named after the association, `questions_attributes=`, so `questions_attributes` becomes an assignable key for `new`, `create`, `update` and `assign_attributes`. - It sets **autosave** on the `questions` association, which means the survey's validation and save also validate and save the questions held in memory. - It records the options (`allow_destroy:`, `reject_if:`, `limit:`, `update_only:`) that steer the writer. The macro looks the association up when it runs, so it must come after `has_many :questions`; otherwise it raises `ArgumentError` asking whether the association has been defined yet. It works for `has_many` and for one-to-one links (`has_one`, `belongs_to`), whose writer takes a single hash. ## The payload shapes | Shape | Example value for `questions_attributes` | How it is read | |---|---|---| | Array of hashes | `[{ prompt: "Role?" }, { id: 4, prompt: "Team?" }]` | each hash is one question | | Hash of hashes | `{ "0" => { prompt: "Role?" }, "1" => { prompt: "Team?" } }` | the keys are ignored, each value is one question | | One hash with an `id` key | `{ id: 4, prompt: "Team?" }` | treated as a single question | The hash-of-hashes shape is what an HTML form submits, because form fields have no natural way to express an array of hashes. Within each hash, `id` and `_destroy` are control keys that are never assigned as attributes. ## What a save does 1. **Assignment.** A hash without `id` builds a new question in `survey.questions`. A hash with an `id` finds that question among the survey's own questions and assigns the new values to it in memory; nothing is written yet. 2. **Validation.** Saving the survey validates it and, through autosave, the questions it is about to save. 3. **Writes.** The survey row is inserted or updated; then questions marked for destruction are destroyed, and each new or changed question is saved with `survey_id` pointing at the survey. 4. **Atomicity.** All of this happens inside the transaction the survey's save opened, so a failure anywhere leaves no partial survey behind. ## Where the writer is called from The generated writer is an ordinary attribute writer, so every mass-assignment entry point reaches it: - `Survey.new(attrs)` and `Survey.create(attrs)` build the questions while building the survey. - `survey.update(attrs)` assigns and saves inside one transaction, which also covers any side effects of the assignment. - `survey.assign_attributes(attrs)` only assigns; nothing is written until `save`. - Calling `survey.questions_attributes = [...]` directly is the same as any of the above for just that key. In a typical request, the controller hands the permitted survey parameters to one of these calls and then checks the boolean result of the save, exactly as it would for a model without children. ## Nesting a level deeper `Question` can declare `accepts_nested_attributes_for :choices` in turn. A single payload then carries a survey, its questions and each question's choices: `questions_attributes: [{ prompt: "Role?", choices_attributes: [{ label: "Engineer" }, { label: "Designer" }] }]`. Autosave cascades, so one `survey.save` writes rows in three tables. ## Traps - **Ids are scoped to the parent.** The writer looks ids up within this survey's questions, so an id belonging to another survey raises `ActiveRecord::RecordNotFound` with a message naming both models, rather than moving that question. - **Updating children while creating the parent fails.** A brand-new survey has no questions to match, so a hash with an `id` on `Survey.create` raises the same error. - **Only mentioned children change.** Questions not listed in the payload are left as they are; nested attributes do not replace the collection. - **The writer is only half the feature.** The form side and the controller's permitted keys for `questions_attributes`, including `id` and `_destroy`, are configured elsewhere and must match what the model accepts.
- What happens if questions_attributes contains an id that belongs to another survey?The writer looks ids up only among this survey's questions, so it raises `ActiveRecord::RecordNotFound` with a message naming the question id and the survey. It never fetches the foreign question and re-parents it.
- Why must accepts_nested_attributes_for come after has_many :questions in the class body?The macro reads the association's reflection when it runs, to switch on autosave and pick a collection or one-to-one writer. If `has_many :questions` is not declared yet, it raises `ArgumentError` asking whether the association has been defined.
- How is the hash of hashes from a form different from an array of hashes?Only in shape. The writer takes the values of a hash of hashes and ignores keys such as `"0"` and `"1"`, unless the hash itself has an `id` key, in which case it is treated as one record. Both shapes produce the same questions.
- Assigning questions_attributes inserts each new question row immediately.
- The survey and its questions save in separate transactions, so a failing question leaves the survey behind.
- A hash without an id updates the first existing question.
- Keys like "0" and "1" in questions_attributes become the questions' ids.
- accepts_nested_attributes_for :questions can be declared before has_many :questions.