Add/remove nested fields with Stimulus (no cocoon)

10720
0

Nested fields are a common Rails pain point, and the old solution was heavy JS gems. With Stimulus, I keep it minimal: render a hidden <template> containing the fields with a placeholder index, then on “Add” clone it and swap the placeholder for a timestamp. Removing fields either deletes the node (new records) or sets the _destroy hidden input (existing records). This works nicely with Turbo because the controller is attached to the form and survives replacements. It’s also easy to unit test in the browser: click add, ensure the inputs exist. The key is being consistent with naming and using fields_for to generate correct param structure.