skip to content

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%

answer

  1. appended after the block's output
  2. lands between </tr> and <tr>
  3. hidden_field :id inside a cell
  4. builder skips a second id
  5. include_id: false means no id at all

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.

solid answer

~40 s

For each persisted child, `fields_for` captures the block's HTML and then concatenates `hidden_field(:id)` after it. If the block renders `<tr>...</tr>`, the hidden input sits between rows, where a table body allows only rows, and it lives outside the element a script or a Turbo Stream would hide, move or replace. The fix is to place the id yourself: call `ingredient_fields.hidden_field :id` inside a `<td>`. The builder records that it emitted the id and skips its automatic one, so `include_id: false` is optional there. You need `include_id: false` when the child must post no id at all: children that are not identified by an id the update can use, or a form that copies another cocktail's saved ingredients as starting values for a new one, where posting their ids would make nested attributes raise `ActiveRecord::RecordNotFound`.

code

erb · 13 lines
erb
<%= form_with model: @cocktail do |f| %>
  <table>
    <tbody>
      <%= f.fields_for :ingredients, @source.ingredients, include_id: false do |ingredient_fields| %>
        <tr>
          <td><%= ingredient_fields.text_field :name %></td>
          <td><%= ingredient_fields.text_field :amount %></td>
        </tr>
      <% end %>
    </tbody>
  </table>
  <%= f.submit "Create copy" %>
<% end %>

go deeper

for a junior

Recall that fields_for adds a hidden id for saved children and that include_id: false switches it off.

for a middle

Explain that the id is appended after the block's output, how that breaks table markup, and why a manual hidden_field :id suppresses the automatic one.

for a senior

Spot the stray-id bug in table layouts and DOM scripts, and use include_id: false deliberately for copy flows where foreign ids would raise RecordNotFound.

for a principal

Set conventions for nested-form partials, such as always placing the id explicitly, so table layouts, scripts and Turbo Streams treat a row as one unit.

## Where the automatic id goes `fields_for` renders each child in two steps: 1. It captures whatever the block produced. 2. If the child is persisted and `include_id` is not false, it concatenates `hidden_field(:id)` **after** that output, unless the block already emitted an id. In a list of `<div>` rows that position is harmless. In a table it is not: ```html <tbody> <tr><td><input name="cocktail[ingredients_attributes][0][name]" ...></td></tr> <input type="hidden" name="cocktail[ingredients_attributes][0][id]" value="12" ...> <tr>...</tr> </tbody> ``` A `<tbody>` may contain only rows (and script-supporting elements), so the markup is invalid. It is also fragile: - A script that hides or removes a `<tr>` leaves the row's id behind. - A Turbo Stream that replaces the row by its DOM id replaces the `<tr>` only, not the stray input after it. - Copying or reordering rows in JavaScript moves the row without its identity. The same happens with list markup: a block that renders `<li>` leaves the hidden input directly inside the `<ul>`, which also permits only list items and script-supporting elements. Layouts built from `<div>` rows are the only ones where the default position is invisible. ## Placing the id yourself The cleanest fix keeps the id inside the row: ```erb <%= f.fields_for :ingredients do |ingredient_fields| %> <tr> <td> <%= ingredient_fields.hidden_field :id %> <%= ingredient_fields.text_field :name %> </td> <td><%= ingredient_fields.text_field :amount %></td> </tr> <% end %> ``` The child builder remembers that `hidden_field :id` was called and the parent then skips its automatic one, so the row posts exactly one id. Writing `f.fields_for :ingredients, include_id: false` as well is harmless and makes the intent explicit to a reader. ## When the child should post no id `include_id: false` exists for the cases where an id would be wrong: | Case | Why no id | |---|---| | children without a usable id | the Rails docs' example is comments embedded in a document store with no primary key | | copying a recipe into a new cocktail | the source cocktail's ingredient ids do not belong to the new parent | | the id is placed manually | you already render it where it belongs | The copy case is worth spelling out. Rendering `f.fields_for :ingredients, @source.ingredients` on a new cocktail would post ids of saved ingredients belonging to another cocktail. Nested attributes look a posted id up among the parent's own children, find nothing and raise `ActiveRecord::RecordNotFound`. With `include_id: false` each row posts only its values and becomes a new ingredient on the copy. ## Choosing between the two 1. If the row should keep its identity and you only care **where** the id goes, render `hidden_field :id` inside the row and rely on the builder's duplicate check. 2. If the row must post **no** id, pass `include_id: false` and render none. 3. If you pass `include_id: false` to fix placement, remember to add `hidden_field :id` yourself; otherwise every edited ingredient is posted without an id and becomes a new row on update, leaving the old one in place. ## What include_id does not do - It does not stop an id posted by some other means; tampering protection comes from the parent-scoped lookup just described, which belongs to the nested-attributes leaf. - It does not affect new children, which never get an automatic id. - It does not change names or indexes; only the hidden input is affected. ## Interview summary The automatic id is appended after the block, which breaks table layouts and DOM manipulation that treats the `<tr>` as the row. Put `hidden_field :id` inside a cell and the builder will not add another. Reach for `include_id: false` when a child must post no id, such as copying saved children into a new parent.

  • What happens if you call hidden_field :id inside the block and also leave include_id at its default?
    Only one id is posted. The child builder records that it emitted `:id`, and the parent checks that flag before appending its own hidden field.
  • What does Rails do if a user edits a hidden child id to point at another cocktail's ingredient?
    Nested attributes look the id up only among the parent's own children. An id outside that set raises `ActiveRecord::RecordNotFound`, so the request fails instead of updating someone else's row.

  • fields_for puts the hidden id at the start of the block, inside the row.
  • Calling hidden_field :id in the block posts the id twice unless include_id: false is set.
  • include_id: false also drops the index from the child input names.
  • The id is cosmetic; nested attributes match children by their position.
  • Posting another cocktail's ingredient ids moves those ingredients to this cocktail.