Rails 3 Edit Multiple Records in a Single Form

人走茶凉 提交于 2019-12-18 10:47:19

问题


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.



来源:https://stackoverflow.com/questions/4383391/rails-3-edit-multiple-records-in-a-single-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!