Rails 3 Edit Multiple Records in a Single Form

2019-02-01 03:11发布

问题:

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

回答1:

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



回答2:

The change in Rails 3 from <% fields_for to <%= fields_for is because it was confusing that form_for, form_tag, etc... were using <% form... %> even though they they were outputting html code. With Rails 3, since they output html code, they use <%=.

Please note that your first line is deprecated:

<% form_tag update_individual_products_path, :method => :put do %>

should be

<%= form_tag update_individual_products_path, :method => :put do %>

Same for all form tags.