0

I have a form in Rails which uses fields_for to accept nested attributes:

<%= form_with(model: @combat_tracker, url: form_url) do |f| %>
  …
  <%= f.fields_for :zones do |zone| %>
    <div class="zone-field">
      <%= zone.text_field :name %>
      <%= zone.check_box :_destroy %>
      <%= zone.label :_destroy, "Remove zone" %>
    </div>
  <% end %>
  …
<% end %>

Currently this gives me input fields for any existing zones on @combat_tracker. I want to add a button that will dynamically add a new zone-fields div for a new zone to be added when the form is submitted.

I’m using Rails 7 and assume the solution will involve the use of Turbo or possibly Stimulus, but can’t quite figure out the best way to do this. Thanks.

tsvallender
  • 2,615
  • 6
  • 32
  • 42
  • Shameless plug, maybe it'll help: https://stackoverflow.com/questions/71713303/rails-7-dynamic-nested-forms-with-hotwire-turbo-frames/71715794#71715794. It's a simple set up without js. – Alex May 30 '22 at 07:29

1 Answers1

0

I don't think you need Turbo or Stimulus. Take a look at cocoon gem, it should do exactly what you're looking for.

Explaining all process here is quite complex for me, but try to follow this guide if the gem's one is too long.

Vi.
  • 940
  • 6
  • 24