这只是购物车中用于更新数量的提交表单。但是,更新后的数量不会保存到数据库中 - 它总是使数量为0.请帮助。
表格
<% for line_item in @cart.line_items %>
<% form_for :lineitems, :url => {:controller => "line_items", :action => "cart_update", :id => "#{line_item.product_id}"} do |l| %>
<%= l.text_field :quantity, :size => '3', :value => line_item.quantity %>
<%= l.submit 'cart_update' %>
<% end %>
路线
map.connect 'line_item_update', :controller => 'line_items', :action => 'cart_update'
控制器
def cart_update
@product = Product.find(params[:id])
item = LineItem.find_or_create_by_cart_id(:cart_id => current_cart.id, :product_id => @product.id, :quantity => 0, :unit_price => @product.price)
item.quantity = (params[:quantity]).to_i
item.save
redirect_to :controller => 'products'
end
答案 0 :(得分:0)
首先,您需要将视图更改为以下内容:
<% form_for :lineitems, :url => {:controller => "line_items", :action => "cart_update" do |l| %>
<% @cart.line_items.each_with_index do |line_item, index| %>
<% fields_for "@cart.line_items[#{index}]", line_item do |i| %>
<%= i.text_field :quantity, :size => '3', :value => line_item.quantity %>
<% end %>
<% end %>
<%= l.submit 'cart_update' %>