Form within loop duplicates fields_for object multiplied how many loop results in asc order

375 Views Asked by At

My form for new records is creating duplicates of the fields_for iteration per loop.

For instance:

I have a form within a loop, so for each result, there is a form for that result.

Is there are 3 results:

The first result will have correct fields_for objects The second form will have x2 fields_for objects (duplicates of each object) The third form will have x3 fields_for objects (2 extra of each object)

I have a form which needs to loop through a has_many ... through: association.

Form:

<%= form_for @shop_product do |f| %>
<% PrintLocation.all.each{|p|@shop_product.shop_product_print_files.build(print_location: p)}  %>
    <%= f.fields_for :shop_product_print_files do |ff| %>
        <%= ff.object.print_location.title %>
    <% end %>
    <%= f.submit %>
<% end %>

This creates x(loop_result) of the print_location's object.

Once I create the @shop_product, this issue goes away because i use the following form for editing:

<%= form_for shop_product do |f| %>
<% PrintLocation.all.each{|p| shop_product.shop_product_print_files.build(print_location: p) if shop_product.shop_product_print_files.where(print_location: p).empty? } %>
    <%= f.fields_for :shop_product_print_files do |ff| %>
        <%= ff.object.print_location.title %>
    <% end %>
    <%= f.submit %>
<% end %>

This eliminates any duplicates. I tried this for new form, but didn't work. I tried using distinct on the PrintLocation.each, but that caused errors, undefined method "distinct".

Model:

**shop_product**
  has_many :shop_product_print_files
  has_many :print_locations, through: :shop_product_print_files
  accepts_nested_attributes_for :shop_product_print_files, reject_if: :reject_file, :allow_destroy => true

Why are duplicates x (loop_result.count) of fields_for object appearing and how can I solve this from happening?

1

There are 1 best solutions below

0
Lachlan Priest On

I believe the double looping was due to an extra equals in <%= f.fields_for record do |ff| %>.

Could you please try this:

<%= form_for shop_product do |f| %>
  <% PrintLocation.find_each do |p| %>
    <% record = shop_product.shop_product_print_files.where(print_location: p).first_or_initialize %>

    <% unless record.persisted? %>
      <% f.fields_for record do |ff| %>
        <%= ff.object.print_location.title %>
      <% end %>
      <%= f.submit %>
    <% end %>
  <% end %>
<% end %>