我有一个rails应用程序,我希望一次更新多个记录的相同字段。这是我在视图中的表单
<tbody>
<%= form_tag update_cart_cart_path, method: "PUT" do |f| %>
<% @cart_items.each do |cart_item| %>
<tr class="items">
<td><a class="remove" href="#"><fa class="fa fa-close"></fa></a></td>
<td><%= image_tag cart_item.variant.variant_photos[0].variant_image %></td>
<td><a class="aa-cart-title" href="#"><%= cart_item.variant.name %></a></td>
<td>Rs. <%= cart_item.variant.price %>/kg</td>
<td><%= fields_for "cart_items[#{cart_item.id}]" do |p| %>
<%= p.text_field 'quantity' %>
<% end %></td>
<td><input class="aa-cart-quantity product-quantity" rel="<%= cart_item.variant.price %>" type="number" value="<%= cart_item.quantity %>"></td>
<td>Rs. <%= (cart_item.variant.price) * (cart_item.quantity) %></td>
</tr>
<% end %>
<td colspan="6" class="aa-cart-view-bottom">
<input type="submit" value="submit">
<%#= link_to 'Update Cart', '#', :class => 'hvr-shutter-in-horizontal button' %>
</td>
</tr>
<% end %>
</tbody>
我的控制器是
def update_cart
@cart_items = CartItem.where(cart_id: params[:id])
@cart_items.each do |item|
item.update_attributes(update_cart_params)
end
end
private
def update_cart_params
params.require(:cart_items).permit!
end
现在我面临的问题是,当我尝试更新cart_item记录时,我收到错误消息unknown attribute '2' for CartItem.
这些是我提交后提交的参数
Parameters: {"utf8"=>"✓", "authenticity_token"=>"5dlZZhW5UCw+dZfalPnqQmNKzkNHVLcwvt8luitOE7NojtkFDmdwwTzKi+DrFioOrpG8gcekRuQRZYYj0OKJHg==", "cart_items"=>{"2"=>{"quantity"=>"121"}, "3"=>{"quantity"=>"111"}}, "id"=>"1"}
请帮助
答案 0 :(得分:3)
问题在于您尝试使用所有购物车项目的参数更新每个购物车商品。
您应该尝试以下方法:
伪代码,未经过测试,但您会明白这一点:
def update_cart
@cart = Cart.find(params[:id])
update_cart_params.keys.each do |cart_item_id|
cart_item = @cart.items.find(cart_item_id)
if cart_item
cart_item.update(update_cart_params[cart_item_id])
end
end
end