1

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
lessless
  • 866
  • 10
  • 27

1 Answers1

0

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
Nico
  • 881
  • 1
  • 6
  • 19
  • but that will create lots of forms, isn't it? how to commit changes with one submit than? – lessless Apr 24 '15 at 15:47
  • Yes, that is true each form will need to be submitted separately. Having only one form would only work when categories are field sets too. I'll try to come up with an example. – Nico Apr 24 '15 at 19:26