我在获取 has_many 关联的表单以用于购物篮时遇到了一些麻烦。该 View 显示购物篮,并且每个项目都有一个表行。每行包含一个文本字段,以便用户可以设置数量。
问题在于,即使第二个项目的数量也发生了变化,参数中也仅传递了第一个项目行的数量。
有人可以帮忙吗?
谢谢, 罗杰
调试器中 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"}
应用程序/ Controller /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
helper和nested_attributes_for
- 请参阅NestedAttributes还可以了解更多信息。
关于ruby-on-rails - Rails 有多种形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6335116/