views:

13

answers:

1

Hey guys, I've been trying to understand the documentation and find an example, but I'm at a loss.

This is just a submit form within the cart for updating the quantity. However, the updated quantity is not getting saved to the database -- it always makes the quantity 0. Please help.

Form

<% 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 %>

Route

map.connect 'line_item_update', :controller => 'line_items', :action => 'cart_update'

Controller

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
A: 

For a start you need to change the view to something like this:

<% 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' %>
thomasfedb
This forum post may help you: http://railsforum.com/viewtopic.php?id=2696
thomasfedb