Rails 3 Edit Multiple Records in a Single Form

chris__allen picture chris__allen · Dec 8, 2010 · Viewed 13.8k times · Source

I've been stuck on this problem for a couple of days now.

I've have some success with Railscasts Episode #198, but that one is for Rails 2. There have been some changes in Rails 3 that make it so the code provided in Episode #198 won't work.

The problem lies within the edit_individual.html.erb:

Original Code (provided by Ryan @ Railscasts):

<% form_tag update_individual_products_path, :method => :put do %>
  <% for product in @products %>
    <% fields_for "products[]", product do |f| %>
      <h2><%=h product.name %></h2>
      <%= render "fields", :f => f %>
    <% end %>
  <% end %>
  <p><%= submit_tag "Submit" %></p>
<% end %>

Modified Code (simply changed fields_for to form_for):

<% form_tag update_individual_products_path, :method => :put do %>
  <% for product in @products %>
    <% form_for "products[]", product do |f| %>
      <h2><%=h product.name %></h2>
      <%= render "fields", :f => f %>
    <% end %>
  <% end %>
  <p><%= submit_tag "Submit" %></p>
<% end %>

In the new code, each record is placed within a form of their own, all inside one single form (which is the one I only want).

My question is, how can I get the code provided by Railscasts Episode #198 to work in Rails 3?

Here is a link to the Railscast I mentioned: http://railscasts.com/episodes/198-edit-multiple-individually

Thank You, c.allen.rosario

Answer

chris__allen picture chris__allen · Dec 9, 2010

I found the solution. Just need to modify the following line in the code provided by Ryan @ Railscasts:

<% fields_for "products[]", product do |f| %>

and change it to:

<%= fields_for "products[]", product do |f| %>

Notice, that the <% has been modified to <%=.

final solution:

<% form_tag update_individual_products_path :method => :put do %>  
  <% for product in @products %>  
    <%= fields_for "products[]", product do |f| %>  
      <h2><%= h product.name %></h2>  
    <% end %>  
  <% end %>  
  <p><%= submit_tag "Submit" %></p>  
<% end %>  

I was wondering if anyone could explain this solution to me. From what I understand you should only need a <% in front of the fields_for.

c.allen.rosario