skip to content

Child Record Fields

fields_for nests a child's inputs under names like post[comments_attributes][0][body] with hidden ids, and a _destroy box marks rows for removal. Interviewers probe those names and dynamic rows.

part ofRuby on Railsread it →
on this pageshow

explore

questions

5

In a Rails form, what input names does f.fields_for :ingredients produce for a has_many association, and when is a hidden id field added?

level: middleimportance: must knowfreq 55%

answer

  1. respond_to? ingredients_attributes=
  2. cocktail[ingredients_attributes][0][name]
  3. a counter from 0, not the id
  4. hidden id only for persisted children
  5. empty association renders nothing

basics

~10 s

When Cocktail responds to ingredients_attributes=, f.fields_for :ingredients repeats its block per ingredient with names like cocktail[ingredients_attributes][0][name], then [1], and so on. Saved ingredients also get a hidden [id] input; new ones do not.

solid answer

~40 s

`FormBuilder#fields_for` first checks whether the parent responds to `ingredients_attributes=`, the writer `accepts_nested_attributes_for` defines. If it does and the association is a collection, it yields a child builder once per record, naming inputs `cocktail[ingredients_attributes][0][amount]` with ids like `cocktail_ingredients_attributes_0_amount`. The index is a per-association counter starting at 0, not the database id; `child_index:` overrides it and the child builder exposes it as `index`. For every persisted child it appends a hidden `[id]` input after the block's output, which is how the update matches each hash to an existing row; new children get none and become inserts. An empty association renders nothing, so the `new` action builds blank children, for example `3.times { @cocktail.ingredients.build }`. A `has_one` follows the same rules without the index: `cocktail[garnish_attributes][name]`.

code

erb · 17 lines
erb
<%= form_with model: @cocktail do |f| %>
  <%= f.text_field :name %>

  <%= f.fields_for :ingredients do |ingredient_fields| %>
    <div class="ingredient">
      <%= ingredient_fields.label :name, "Ingredient #{ingredient_fields.index + 1}" %>
      <%= ingredient_fields.text_field :name %>
      <%= ingredient_fields.text_field :amount %>
    </div>
  <% end %>

  <%= f.fields_for :garnish do |garnish_fields| %>
    <%= garnish_fields.text_field :name %>
  <% end %>

  <%= f.submit %>
<% end %>

go deeper

for a junior

Recall the shape cocktail[ingredients_attributes][0][name], that the block repeats per child, and that the controller must build children for a new record.

for a middle

Explain the respond_to? check on the _attributes= writer, the per-association counter index, and why only persisted children get a hidden id appended after the block.

for a senior

Use the naming rules to debug real forms: rows missing on new, plain scoped names when the writer is absent, and colliding indexes that silently merge two rows.

for a principal

Judge when a nested form is the right tool at all versus a separate screen or form object per child, given validation, authorisation and UX costs.

## What `fields_for` checks first `FormBuilder#fields_for`, the method you call as `f.fields_for` inside `form_with`, asks one question before it renders anything: does the parent object respond to `<association>_attributes=`? That writer is what `accepts_nested_attributes_for :ingredients` defines on the `Cocktail` model (the model side belongs to the nested-attributes leaf). The answer picks the naming mode: | Parent responds to the writer? | Names produced | How often the block runs | |---|---|---| | yes, `has_many :ingredients` | `cocktail[ingredients_attributes][0][name]`, `[1]`, ... | once per child record | | yes, `has_one :garnish` | `cocktail[garnish_attributes][name]` | once, if the child exists | | no | `cocktail[ingredients][name]` | once, with no record bound | The last row is a plain scope. For an association it is almost never what you want, because the association writer expects records, not a hash of strings. ## The names a has_many produces For a collection, the builder iterates the association (or the collection you pass as the second argument) and yields a child `FormBuilder` for each record: - **Name prefix**: `cocktail[ingredients_attributes][INDEX]`, so `text_field :name` becomes `cocktail[ingredients_attributes][0][name]`. - **Ids**: the same path joined with underscores, `cocktail_ingredients_attributes_0_name`, so each `label` points at its own row's input. - **The index** is a counter the parent builder keeps per association name, starting at `0`. It is **not** the record's database id. The child builder exposes it through `index`, and the `child_index:` option replaces it. - **Values** are read from each child record, so an edit form shows the saved amounts and a re-rendered form shows what the user typed. ## The hidden id field For every child whose `persisted?` is true, the builder appends a hidden input **after** the block's own output: ```html <input autocomplete="off" type="hidden" value="12" name="cocktail[ingredients_attributes][0][id]" id="cocktail_ingredients_attributes_0_id"> ``` 1. On update, that `id` ties a posted hash to an existing ingredient; a hash without an id is treated as a new child. 2. Unsaved children get no hidden id. 3. If the block already calls `ingredient_fields.hidden_field :id`, the builder notices and does not add a second one. 4. `include_id: false` turns the automatic field off when you place it yourself or want none at all. ## Showing rows on a new record Because the block runs once per child, a brand-new cocktail with no ingredients renders **nothing** in that section. The usual fix lives in the controller: ```ruby def new @cocktail = Cocktail.new 3.times { @cocktail.ingredients.build } @cocktail.build_garnish end ``` `build` adds unsaved children to the in-memory association, so three blank rows appear, and `build_garnish` does the same for the `has_one`. After a failed save the children assigned from the submitted params are still on `@cocktail`, so the re-rendered form shows the same rows with the user's input. ## What the controller receives The bracketed names make Rails' parameter parser build nested hashes, with each index as a string key: ```ruby { "cocktail" => { "name" => "Paloma", "ingredients_attributes" => { "0" => { "id" => "12", "name" => "Tequila", "amount" => "50 ml" }, "1" => { "name" => "Grapefruit soda", "amount" => "top up" } } } } ``` Two consequences come up in interviews: - The keys only need to be **unique**. Two rows posting the same index collapse into one hash, and the later values win. - Permitting this shape belongs to the strong-parameters leaf. In Rails 8 it reads `params.expect(cocktail: [:name, ingredients_attributes: [[:id, :name, :amount]]])`, and the double brackets accept a hash whose keys are integer strings. ## Edge cases interviewers probe - **The counter is shared per association.** The parent builder keeps one counter for each `*_attributes` name, so a second `f.fields_for :ingredients` call in the same form continues at the next index instead of restarting at `0`. - **Re-renders renumber.** After a failed save the rows are rendered from the counter again, `0` upward in the association's order, whatever keys the browser posted. - **Nesting goes deeper.** If `Ingredient` also accepts nested attributes for `substitutions`, a `fields_for :substitutions` inside the ingredient block produces `cocktail[ingredients_attributes][0][substitutions_attributes][0][name]`. - **A wrong association name fails quietly.** `f.fields_for :ingredient` (singular) finds no `ingredient_attributes=` writer and falls back to the plain scope, so the form renders one unbound set of fields instead of raising. ## Interview summary `fields_for` is a naming machine. Given a nested-attributes association it produces `*_attributes` names with a per-row index, binds each row to a child record, and adds a hidden id for saved children. Everything the model then does with those params happens in `accepts_nested_attributes_for`, not in the view.

  • What names does fields_for produce for a has_one :garnish, and what if the cocktail has no garnish yet?
    With `accepts_nested_attributes_for :garnish` the names carry no index: `cocktail[garnish_attributes][name]`, plus a hidden `[id]` when the garnish is saved. If `@cocktail.garnish` is nil the block does not run at all, so the `new` action calls `@cocktail.build_garnish` to get a blank set of fields.
  • Can you render only some of the children, or a collection other than the association?
    Yes. Pass the records as the second argument: `f.fields_for :ingredients, @cocktail.ingredients.reject(&:new_record?)` iterates that collection, still with `ingredients_attributes` names and a counter index. Passing a single record, such as `Ingredient.new`, renders one block for it.
  • Why does params show a hash keyed "0", "1" instead of an array?
    The index sits inside brackets in each name, so Rails' parameter parser builds a hash with string keys. `accepts_nested_attributes_for` accepts either a hash or an array, and `params.expect` with `ingredients_attributes: [[...]]` accepts a hash only when its keys are integer strings.

  • fields_for names child inputs cocktail[ingredients][][name], so the params arrive as an array.
  • The index in each child name is the ingredient's database id.
  • fields_for adds the hidden id input for every child, saved or not.
  • fields_for shows one blank row on its own when the association is empty.
  • fields_for uses _attributes names for any association, even without accepts_nested_attributes_for.
open as a page

In a Rails nested form, how does a _destroy checkbox inside fields_for remove a saved child record, and what must be in place?

level: middleimportance: should knowfreq 45%

basics

~10 s

Inside fields_for, f.checkbox :_destroy posts cocktail[ingredients_attributes][0][_destroy] as 1 when ticked, beside the row's hidden id. The parent's accepts_nested_attributes_for needs allow_destroy: true, and the row is deleted only when the parent saves.

open as a page

In a Rails nested form, how do you render a template for new ingredient rows so JavaScript can add any number of them without name collisions?

level: seniorimportance: should knowfreq 40%

basics

~10 s

Render one blank child inside a <template> with f.fields_for :ingredients, Ingredient.new, child_index: "NEW_RECORD". JavaScript clones it and replaces NEW_RECORD with a fresh number such as Date.now(), so every added row gets unique names.

open as a page

In a Rails form_with block, how do you group inputs under their own key, such as cocktail[launch][announce], when no model or association backs them?

level: juniorimportance: nice to knowfreq 20%

basics

~20 s

Call form.fields :launch and build inputs on the builder it yields, which names them cocktail[launch][announce]. It renders no form tag and no hidden id, and fields start blank unless you pass model: with an object to read from.

open as a page

In a Rails nested form that renders each ingredient as a table row, why does the automatic hidden id end up outside the row, and when do you pass include_id: false?

level: seniorimportance: nice to knowfreq 15%

basics

~20 s

fields_for appends the hidden id after the block's output, so when the block renders a <tr> the input lands between rows. Render f.hidden_field :id inside a cell, or pass include_id: false when the child should post no id.

open as a page