skip to content

When a Rails survey saved with nested questions fails validation, how do the child errors reach the survey, and what gets written?

level: seniorimportance: should knowfreq 35%

answer

  1. autosave validates the children
  2. errors keyed questions.prompt
  3. index_errors: for questions[1].prompt
  4. one transaction, nothing written
  5. inverse lets survey must exist pass

basics

~20 s

Nested attributes turn on autosave, so validating the survey also validates its new and changed questions and copies their errors onto the survey as keys like questions.prompt. The save returns false and nothing is written.

solid answer

~40 s

`accepts_nested_attributes_for :questions` enables autosave, and autosave adds a validation step: for a new survey every question in memory is validated, for an existing one every question that is new, changed or nested-changed. Each child error is wrapped as a nested error on the survey under `questions.prompt`. Setting `index_errors: true` on `has_many :questions` gives `questions[1].prompt` in association order, `index_errors: :nested_attributes_order` uses the payload's order, and `config.active_record.index_nested_attribute_errors` sets the default, which is false. Because validation runs before any write and everything shares the survey's transaction, a failed `save` writes nothing; `save!` raises `ActiveRecord::RecordInvalid`. Questions marked for destruction are skipped. A "must exist" error on `questions.survey` means the new question cannot see its unsaved survey: the inverse was not detected, so add `inverse_of: :survey`.

code

ruby · 19 lines
ruby
class Survey < ApplicationRecord
  has_many :questions, index_errors: :nested_attributes_order,
                       inverse_of: :survey, dependent: :destroy
  accepts_nested_attributes_for :questions, allow_destroy: true

  validate :has_a_question

  private
    def has_a_question
      if questions.reject(&:marked_for_destruction?).empty?
        errors.add(:questions, "must include at least one question")
      end
    end
end

survey = Survey.new(title: "Pulse",
                    questions_attributes: [{ prompt: "Role?" }, { prompt: "" }])
survey.save                    # => false, nothing written
survey.errors.attribute_names  # => [:"questions[1].prompt"]

go deeper

for a junior

Recall that an invalid nested question makes the whole survey save return false and that its message shows up in survey.errors.

for a middle

Explain autosave validation, the questions.prompt error keys, the index_errors choices, and why nothing is written when a child fails.

for a senior

Diagnose the production cases: "must exist" from a missing inverse, mismatched error indexes on updates, and child-count rules that forget marked records.

for a principal

Weigh deep nested validation in models against a form object that validates the whole submission and reports errors in the shape the UI needs.

## Why the children are validated at all `accepts_nested_attributes_for` switches on **autosave** for the association, and autosave registers a validation on the parent that walks the associated records held in memory. Which records it checks depends on the parent's state: - For a **new survey**, every question in the loaded collection is validated. - For an **existing survey**, only questions that are new, have unsaved changes, are marked for destruction, or have nested changes of their own are considered. - Questions **marked for destruction** are skipped, so a doomed invalid row cannot block the delete. There is no need to add `validates_associated :questions`; autosave already does that work. ## How the errors are named When a question is invalid, each of its errors is wrapped in a nested error object and appended to the survey's errors. The attribute name records the path: | Setting | Error key on the survey | |---|---| | default | `questions.prompt` | | `has_many :questions, index_errors: true` | `questions[1].prompt`, index in association order | | `has_many :questions, index_errors: :nested_attributes_order` | `questions[1].prompt`, index in the order the hashes arrived | | `config.active_record.index_nested_attribute_errors = true` | indexed keys for every `has_many` without its own setting; the default is false | With association order, records already in the database come first and new ones are appended, so an index may not match the row the user typed into. `:nested_attributes_order` exists for that case. Choices nested under questions produce deeper paths, such as `questions.choices.label`. ## What gets written 1. `survey.save` runs the survey's own validations and the autosave validation together. 2. If any question is invalid, `save` returns `false` before a single `INSERT` or `UPDATE`, and `save!` raises `ActiveRecord::RecordInvalid`. 3. If validation passes, the survey row and every child write happen inside one transaction, so a failure at the database, such as a unique-index violation on a question, rolls back the survey as well. The invalid questions are still in `survey.questions` in memory with their own errors, which is what lets a form re-render them with messages beside the right fields. ## Reporting the errors Each nested error keeps the child's own error inside it, so code can reach the original object and message, and `survey.errors.full_messages` still produces readable text. The attribute part of the message is looked up as `activerecord.attributes.survey/questions.prompt` in the locale files; without a translation it falls back to the humanised child attribute, so the message reads "Prompt can't be blank". Two consequences follow: - Two nested associations with the same column name produce identical full messages unless the locale distinguishes them. - A form that wants messages beside each row should read the indexed keys or the child records' own errors, not the flat list. ## The parent-presence trap A new `Question` declares `belongs_to :survey`, which is required by default. When a brand-new survey and its questions are validated together, the survey has no id yet, so the check can only pass if `question.survey` already points at the in-memory survey. Building through the association sets that link through the **inverse**: - With plain `has_many :questions` and `belongs_to :survey`, Rails finds the inverse automatically. - Options such as `foreign_key:` on the `has_many` stop automatic detection, and the result is a "must exist" error on `questions.survey`. - The fix is to declare `inverse_of: :survey` on the `has_many`, so built questions know their survey before it is saved. ## Rules that count children A rule such as "a survey needs at least one question" has a nested-attributes twist: questions marked for destruction are still in the collection until the save. A count that includes them lets a user delete every question and still pass. Count `questions.reject(&:marked_for_destruction?)` instead.

  • Why can index_errors: true point at the wrong form row on an update?
    With `true` the index follows association order: loaded questions in database order, with new ones appended. The form's rows may be ordered differently, so `questions[2].prompt` may not be the third row the user sees. `index_errors: :nested_attributes_order` indexes by the order the hashes arrived instead.
  • Do you need validates_associated :questions when the survey accepts nested attributes for them?
    No. Nested attributes turn on autosave, and autosave already validates the new and changed questions and copies their errors onto the survey. Adding `validates_associated` validates them a second time.

  • The survey row is saved first and only the invalid questions are left out.
  • Child errors stay on the questions and never appear in survey.errors.
  • You must add validates_associated :questions for nested children to be checked.
  • A question marked for destruction can still block the save with its own errors.
  • Errors are indexed like questions[1].prompt in every Rails app by default.