Edit 11.12.2024: I’ve updated turbo stream responses to include field index.
Recently I was working on implementing dynamic nested forms using Turbo Streams, focusing on handling both new and persisted records without custom JavaScript. Well, mostly for fun, to try something new. And while there are multiple approaches to this problem, including Stimulus controllers or plain JavaScript, Turbo Streams offer a clean, server-driven solution that leverages Rails conventions.
The Core Concept: Form Manipulation vs Persistence
A key aspect of this implementation that might not be immediately obvious is that the IngredientsController
doesn’t actually persist any data. Its sole responsibility is to manipulate the form structure through Turbo Stream responses.