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?
answer
- one unsaved child, rendered once
- child_index: "NEW_RECORD"
- a <template> element stays inert
- replace the placeholder with Date.now()
- keys must be unique integer strings
basics
~10 sRender 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.
solid answer
~40 sPassing a single unsaved `Ingredient.new` to `f.fields_for :ingredients` renders one set of child fields, and `child_index: "NEW_RECORD"` replaces the counter, giving names like `cocktail[ingredients_attributes][NEW_RECORD][name]`. Wrapped in a `<template>` element, that markup is neither shown nor submitted. A small script, usually a Stimulus controller in a Rails 8 app, clones the template's HTML, replaces every `NEW_RECORD` with a new number such as `Date.now()`, and inserts it. The number must be unique, because two rows with the same index post the same keys and the later values overwrite the earlier ones. It must also be digits, because `params.expect` with `ingredients_attributes: [[...]]` keeps only integer-string keys, so an unreplaced placeholder row is dropped. The new row has no hidden id, since the record is unsaved, and becomes an insert.
code
erb · 13 lines<div data-controller="ingredients">
<%= f.fields_for :ingredients do |ingredient_fields| %>
<%= render "ingredient_fields", f: ingredient_fields %>
<% end %>
<template data-ingredients-target="template">
<%= f.fields_for :ingredients, Ingredient.new, child_index: "NEW_RECORD" do |ingredient_fields| %>
<%= render "ingredient_fields", f: ingredient_fields %>
<% end %>
</template>
<button type="button" data-action="ingredients#add">Add ingredient</button>
</div>go deeper
Recall that new rows come from one blank child rendered with a placeholder child_index, and that each inserted row needs a unique number.
Explain how fields_for renders a single passed record, why <template> keeps the placeholder row out of the submission, and how the index reaches the names.
Anticipate the silent failures, merged rows from duplicate indexes and dropped rows from non-numeric keys, and choose between a client template and a Turbo Stream row.
Decide where dynamic-form logic should live, client templates or server-rendered fragments, given offline needs, latency and how many such forms the team maintains.
## The problem A cocktail-menu form lets the bartender add as many ingredient rows as a recipe needs. Every row's inputs must carry nested-attributes names such as `cocktail[ingredients_attributes][3][name]`, and every row needs its **own** index. The server renders the existing rows; the browser has to produce the extra ones. ## Render one row as a template `f.fields_for` accepts a record as its second argument. Given a single unsaved child for a `has_many` association, it renders exactly one block for it, and `child_index:` replaces the usual counter: ```erb <template data-ingredients-target="template"> <%= f.fields_for :ingredients, Ingredient.new, child_index: "NEW_RECORD" do |ingredient_fields| %> <div class="ingredient"> <%= ingredient_fields.text_field :name %> <%= ingredient_fields.text_field :amount %> </div> <% end %> </template> ``` The output contains `name="cocktail[ingredients_attributes][NEW_RECORD][name]"` and `id="cocktail_ingredients_attributes_NEW_RECORD_name"`. Key points: - **One row, not one per saved child.** Passing a record overrides iteration over the association. - **No hidden id.** The child is not persisted, so `fields_for` adds none, and the posted row becomes an insert. - **`<template>` keeps it out of the form submission.** Its content is not part of the live document, so the placeholder row is neither displayed nor sent. - **`child_index:` may also be a lambda**; the builder calls it for each child, which helps when you render several rows and want computed indexes. ## Swap the placeholder on insert The script that adds a row does three steps: 1. Read the template's `innerHTML`. 2. Replace every `NEW_RECORD` with a fresh number, for example `Date.now()`. 3. Insert the result before the "Add ingredient" button. The Stimulus controller that wires this up is the Stimulus leaf's subject; the contract with Rails is only the placeholder and the names. ## Why the number must be unique and numeric | Index choice | What the server sees | |---|---| | unique digits (`1730198400123`) | one child hash per row, as intended | | the same digits on two rows | one hash; the second row's values overwrite the first | | `NEW_RECORD` left in place | the row is dropped by `params.expect` | - **Collisions merge rows.** Rails' parameter parser builds a hash from the names, so two inputs named `...[5][name]` write the same key and the last one wins. The user typed two ingredients and one is saved. - **Strong parameters want integer keys.** The double-bracket form `ingredients_attributes: [[:name, :amount]]` accepts a hash only through its keys that look like integers, so a non-numeric key is filtered out. - **Order does not matter.** The keys are only identifiers; a timestamp larger than the server-rendered `0`, `1`, `2` is fine. ## Mistakes that ship - **No `child_index:` on the template.** `f.fields_for :ingredients, Ingredient.new` alone takes the next value of the builder's counter, say `3`. Every clone then carries the same `3`, so all added rows collapse into one. - **Replacing only the first placeholder.** The placeholder appears in every `name`, `id` and label `for`, so the script must replace all occurrences (a global regular expression or `replaceAll`). - **Putting the template outside the form builder.** The template must be rendered with the parent builder `f`, or the names lose the `cocktail[...]` prefix. ## After a failed save When validation fails and the form is re-rendered, the added rows come back from the children that nested attributes built, numbered by the builder's counter from `0`. The timestamps the script chose are gone, which is harmless: the template still carries `NEW_RECORD`, so rows added after the re-render get fresh numbers again. ## A server-rendered alternative Instead of a client-side template, the "Add ingredient" button can request a Turbo Stream that appends a row rendered on the server. Outside the parent builder you name the scope yourself: `fields_for "cocktail[ingredients_attributes][#{Time.current.to_i}]", Ingredient.new`. That trades a round trip for keeping every row's markup in one partial; the rules on unique, numeric indexes are the same. ## Interview summary Render one unsaved child with a placeholder `child_index:` inside `<template>`, replace the placeholder with a unique number when inserting, and remember that duplicate indexes merge rows while non-numeric ones are filtered out by strong parameters.
- Why use a <template> element rather than a hidden <div> holding the blank row?Inputs inside a hidden `<div>` are still part of the form, so the placeholder row would be submitted as a blank ingredient. `<template>` content is not part of the live document, so it is neither shown nor posted until the script copies it out.
- How do you read the row index inside the fields_for block, for example to number the rows?The child builder exposes it as `ingredient_fields.index`. For server-rendered rows it is the counter from 0; for the template it is the `child_index:` value, here the literal `NEW_RECORD`, so the visible number is better computed in the script.
- What if two bartenders' tabs each add a row with the same timestamp?Each browser builds its own request, so indexes only need to be unique within one submission. A collision is realistic only when one script inserts two rows in the same millisecond, which a counter appended to the timestamp avoids.
It is a cloakroom pad of blank tickets: each coat needs its own number written on its ticket. Reuse a number and the attendant hangs two coats on one hook, so one coat is lost; leave the number blank and the ticket is thrown away.
- The new-row index has to continue the server's sequence exactly, 3 after 0, 1, 2.
- Any string works as the index, so leaving NEW_RECORD in place is harmless.
- Two rows sharing an index are saved as two ingredients.
- A hidden div is as good as <template>, since hidden inputs are not submitted.
- The new row needs a hidden id field so Rails can insert it.