How to use nested_form_fields with grouped records?

860 Views Asked by At

By default nested_form_fields gem renders all existing records of the specified association jsut under the <% = f.nested_fields_for %> tag.

The question is how to combine nested_form_fields with model grouping by name ( MyModel.all.group_by(&:name) ), so that each group will display records that belong only to the that specific group

-@product_categories.each do |category|
  %h3= category.name
  =f.add_nested_fields_link :products, 'Add Product'
  -category.products.each do |product|
    = f.nested_fields_for :products, product, legend: 'Product' do |product_form|
      = product_form.text_field :name
1

There are 1 best solutions below

2
Nico On

No need to loop over those products in the inner loop. If a category has many products you can do

- @product_categories.each do |category|
  %h3= category.name
  = form_for category do |f|
    = f.add_nested_fields_link :products, 'Add Product'
    = f.nested_fields_for :products, legend: 'Product' do |product_form|
      = product_form.text_field :name

Edit: If you want only one form, you could use a higher level object which has many categories, like:

= form_for @object_with_categories do |f|
  = f.fields_for :categories do |f_cat|
    %h3= f_cat.object.name
    = f_cat.add_nested_fields_link :products, 'Add Product'
    = f_cat.nested_fields_for :products, legend: 'Product' do |product_form|
       = product_form.text_field :name