Skip to content

Dynamic nested form for awesome nested set

Pili G edited this page Jan 4, 2024 · 5 revisions

Awesome nested set is great to use with cocoon as you can create as many fields as you need and also remove them. Cocoon uses JQuery but you can use vanilla js with this cocoon-js-vanilla

Basic Example of how it works:

Category model

class Category < ApplicationRecord
  acts_as_nested_set(dependent: :destroy)
  has_many :subcategories, class_name: "Category", foreign_key: "parent_id"
end

app/views/categories/new.html.erb

<%= form_with(model: @category) do |form| %>
  <%= form.label :name %>
  <%= form.text_field :name %>

  <h3>Subcategories</h3>
  <div id="subcategories">
    <%= form.fields_for :subcategories do |subcategory_form| %>
      <%= render 'subcategory_fields', f: subcategory_form %>
    <% end %>
    <div class="links">
      <%= link_to_add_association 'Add Subcategory', form, :subcategories %>
    </div>
  </div>

  <%= form.submit %>
<% end %>

app/views/categories/_subcategory_fields.html.erb

<div class="nested-fields">
  <%= f.label :name %>
  <%= f.text_field :name %>
  <%= link_to_remove_association "Remove Subcategory", f %>
</div>