表单数量似乎没有提交

时间:2010-06-18 15:34:40

标签: ruby-on-rails forms shopping-cart

嘿伙计们,我一直在努力理解文档并找到一个例子,但我不知所措。

这只是购物车中用于更新数量的提交表单。但是,更新后的数量不会保存到数据库中 - 它总是使数量为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

1 个答案:

答案 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' %>