skip to content

A Rails volunteer form's summary lists a team error, yet the team select is never marked invalid; why do some errors never appear beside any field?

level: seniorimportance: should knowfreq 30%

answer

  1. lookup is errors[method_name]
  2. belongs_to errors land on :team
  3. the select is :team_id
  4. :base matches no field
  5. nested keys like shifts.starts_at

basics

~20 s

Per-field display looks up errors under the field's own method name. belongs_to :team adds "must exist" under :team while the select is team_id, so nothing matches. :base errors and fields missing from the form behave the same way.

solid answer

~40 s

Both the `field_with_errors` wrapper and any per-field message you print look up `errors[method_name]` for the helper's attribute. A required `belongs_to :team` adds its "must exist" error under `:team`, the association name, but the form renders `form.collection_select :team_id`, so `errors[:team_id]` is empty: the summary lists "Team must exist" and the select stays unmarked. The same gap appears for `:base` errors, for validations on attributes the form has no input for, and on the parent of a nested form, whose copies of child errors use keys like `:"shifts.starts_at"`. Fix it where it shows: print `errors.full_messages_for(:team)` beside the `team_id` select and set `aria-invalid` from `errors.include?(:team)`. A system or integration test that asserts the field's message catches regressions.

code

ruby · 10 lines
ruby
class Volunteer < ApplicationRecord
  belongs_to :team          # required: adds errors[:team] => ["must exist"]
  has_many :shifts
  accepts_nested_attributes_for :shifts
end

volunteer = Volunteer.new(name: "Ana", team_id: nil)
volunteer.valid?                  # => false
volunteer.errors[:team]           # => ["must exist"]
volunteer.errors[:team_id]        # => []

go deeper

for a junior

Recall that a field is marked only when the error uses that field's own attribute name.

for a middle

Explain why belongs_to errors land on the association name, why :base errors appear only in the summary, and how nested errors are keyed on the parent.

for a senior

Diagnose unmarked fields by comparing errors.attribute_names with the helpers' method names, fix the view mapping, and add tests that assert where messages render.

for a principal

Set a convention for association fields and nested forms so error placement is consistent across the app and checked by tests.

## How a field finds its errors Every automatic or hand-written per-field display uses the same key: - The `field_with_errors` wrapper asks the bound object for `errors[method_name]`, where `method_name` is what you passed to the helper (`:team_id` for `form.collection_select :team_id, ...`). - Inline messages you write, such as `form.object.errors.full_messages_for(:email)`, use whatever key you type. The summary, by contrast, loops over **all** errors. So any error stored under a key no field uses shows up in the summary and nowhere else. ## The usual mismatches | Source of the error | Key it uses | Field that does not match | |---|---|---| | required `belongs_to :team` | `:team` | `collection_select :team_id` | | `errors.add(:base, ...)` | `:base` | none, by design | | validation on an attribute without an input, such as a generated `slug` | `:slug` | not in the form | | child record invalid in a nested form | `:"shifts.starts_at"` on the parent | the parent has no such field | | a custom `validate` method that picks a different name | whatever it chose | the real input | ## belongs_to in detail With the defaults a new app loads, `belongs_to` is required. The association builder adds a presence validation on the **association name**, with the `required` message, which renders as "Team must exist". The select writes the **foreign key**. Two reasonable fixes: 1. **Display under both keys.** Beside the select, print `errors.full_messages_for(:team)` and set `aria: { invalid: form.object.errors.include?(:team) }`. A small partial that takes a list of keys handles every association field the same way. 2. **Choose the key in the model.** Make the association `optional: true` and validate `team_id` yourself, accepting that the error then talks about the id and that existence is no longer checked by the association. Option 1 keeps Rails' default validation and is the common choice. ## Nested forms With `accepts_nested_attributes_for :shifts`, an invalid shift adds errors in two places: - on the **child record**, under `:starts_at`; the child fields rendered by `fields_for` are bound to that record, so they are wrapped and can show their own message; - on the **parent**, as nested errors under `:"shifts.starts_at"`, or `:"shifts[0].starts_at"` when the association sets `index_errors: true`; these appear in the parent's summary only. So nested fields usually do get marked, while the parent's summary repeats the message with a dotted key. ## Custom validations choose their own key A hand-written `validate :availability_fits_shift` method decides where its message goes. Adding it with `errors.add(:base, ...)` keeps it in the summary; adding it under the attribute whose input the user must change, for example `errors.add(:available_from, :invalid)`, puts it next to that field. Picking the key is a display decision as much as a validation one, so it is worth agreeing with whoever builds the form. ## Diagnosing a missing marker 1. Print `@volunteer.errors.attribute_names` in the console or a debugger after the failed save, and compare with the method names the form passes to its helpers. 2. Check that the form is bound to the same object that failed, not a fresh one; a `form_with model: Volunteer.new` shows no errors at all. 3. Check the response status and target: a 200 under Turbo, or a 422 rendered into a frame that does not contain the form, shows nothing new. ## Testing the display A controller or integration test can post invalid params and assert both the status and the markup, for example `assert_response :unprocessable_content` followed by `assert_select ".field_with_errors #volunteer_team_id"` when the wrapper is kept, or a check for the message text next to the select. That catches a renamed attribute or association before users do. ## Interview summary Per-field display is a key lookup. Errors whose key no field uses, association names, `:base`, missing inputs and parent-side nested keys, appear only in the summary. Map them to the right input in the view and test that the message lands where the user looks.

  • Why does the summary show "Shifts starts at can't be blank" for a nested child?
    The parent copies each child's error as a nested error whose attribute is `shifts.starts_at`, and `full_message` humanises that key. The child's own fields are marked from the child's errors; the summary line comes from the parent's copy.
  • How would you make every association select show its belongs_to error without repeating code?
    Wrap the pattern in a partial or a custom form builder method that takes the foreign key and the association name, prints `full_messages_for(association)` and sets `aria-invalid` from `errors.include?(association)`. Every select then behaves the same.

  • A required belongs_to :team adds its error under :team_id.
  • field_error_proc marks every field whenever the record has any error.
  • Errors on :base are shown next to the first field of the form.
  • Nested child fields can never be marked, because the errors live on the parent.
  • Renaming the select to :team fixes it, since the builder reads the association.