Rails有多种形式

问题描述

| 我在获取has_many协会的表格来购物篮时遇到麻烦。该视图显示购物篮,并且每个项目都有一个表格行。每行都包含一个文本字段,以便用户可以设置数量。 问题在于,即使第二项的数量也发生了变化,也只有参数中的第一项行数量通过了。 有人可以帮忙吗? 谢谢, 罗杰 下面是调试器中params的输出,仅传递了一个line_item。
(rdb:2624) e params 
{\"commit\"=>\"Recalculate\",\"authenticity_token\"=>\"7TKnhmbBPFiKLzVqTipzH8PDyCrOnKiFixGQ37XDGNY=\",\"_method\"=>\"put\",\"utf8\"=>\"✓\",\"action\"=>\"update\",\"id\"=>\"4\",\"line_item\"=>{\"quantity\"=>\"3\",\"id\"=>\"6\"},\"controller\"=>\"baskets\"}
app / controllers / basket_controller.rb
class BasketsController < ApplicationController
  def update  
    begin
      @basket = Basket.find(params[:id])
      # Can\'t do anything here yet since the correct parameters aren\'t being passed through.
    rescue ActiveRecord::RecordNotFound
      logger.error \"...\"
    end

    redirect_to basket_path
  end
end
app / views / baskets / show.html.erb
<%= form_for @basket do |f| %>
<table id=\"items\">
  <thead>
    <tr>
      <th>Name</th>
      <th>Quantity</th>
      <th>Price</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <% @basket.line_items.each do |item| %>
      <%= form_for item do |g| %>
      <tr class=\"<%= cycle(\'alternate\',\'\') %>\">
        <td><%= item.product.name %></td>
        <td>
          <span class=\"decrement-quantity\"><b>-</b></span>
          <%= g.text_field :quantity %>
          <span class=\"increment-quantity\"><b>+</b></span>
        </td>
        <td class=\"price\"><%= number_to_currency(item.total_price) %></td>
      </tr>
      <% end %>
    <% end %>
      <tr class=\"totals\">
        <td>Total</td>
        <td><%= @basket.total_quantity %></td>
        <td class=\"price\"><%= number_to_currency(@basket.total_price) %></td>
        <td></td>
      </tr>
  </tbody>
</table>
<%= f.submit \'Recalculate\' %>
<% end %>
    

解决方法

        您只是在其他表单中创建一个新表单。 Rails不会做任何神奇的事情,仅仅是因为您将一种表单嵌套在另一种表单中-这就是造成您所看到的问题的原因。 处理这种情况的方法是使用
fields_for
帮助器和
nested_attributes_for
-有关更多信息,请参见NestedAttributes。     ,        我将检查Railscasts:复杂表单的第1部分。观看之后,您可能会对观看第2和3部分感兴趣。 Ryan Bates以易于理解的方式介绍了使用fields_for。