I''ve been working through the Depot application in the Agile Rails
book and was trying my hand at extending the shopping cart so that a
user can change the quantities of items already in the cart.
So to this end I''ve added a form to the display_cart template, with a
form field for the quantity of an item. The relevant code is below
(just showing the embedded erb, not the extra formatting html.
<!-- excerpt of update_cart form -->
<%= form_tag(:action => "update_cart") %>
<% for item in @items
product = item.product -%>
<%= text_field_tag("item[#{product.id}]", item.quantity,
"size" => 2 )%>
<%= submit_tag "Update cart" %>
<!-- end form -->
This calls the ''update_cart'' action method in the store
controller:
def update_basket
@params = params[:item]
@params.each do |key, value|
@basket = find_basket
product = Product.find(key)
count = value.to_i
@basket.update_product(product, count)
end
redirect_to(:action => ''display_cart'')
end
Which in turn relies on the update_product method in the Cart model,
defined thus:
def update_product(product, count)
item = @items.find {|i| i.product_id == product.id}
item.quantity = count
@total_price += (product.price * count)
end
Trouble is, I can''t seem to update the quantity of items in the
session based cart. All the methods run fine *except* the quantity
entered into the form is not being captured in the session. The
problematic line it seems is in the update_product method where I set
''item.quantity = count''
Any clues appreciated. I''m a Ruby newbie so am struggling a little
here!
Richard S