Hi all,
I’m trying to do a small shopping cart and I’ve come across a problem I
believe some of you may consider simple.
I’m basically using two models to do the shopping cart: Orders and
Order_Items
A shopping cart is basically an order (with a state of incomplete) with
each product being an order_item attached to the order. So my shopping
cart page shows the multiple order_items for this particular order - the
cart page itself is an action and view in the Order controller/model.
My problem comes when I try to edit the quantities in the shopping cart.
The only way I’ve gotten close to making changes is by calling the
OrderItem.update() call… see code below:
Orders_Controller.rb
def cart
@order = current_order
end
Order_Items_Controller.rb
def quantity_update
#I would need to pass the params[:quantity] fields instead of
hardcoding the quantities
qtys = {“quantity” => 2}, {“quantity” => 5}, {“quantity” => 3}
OrderItem.update(params[:ids], qtys) #params[:ids] has an array of 3
order_item id’s in this case
end
Cart.html.erb
<% form_tag quantity_update_order_items_path, :method => :put do %>
Product | Qty | Unit Price | Full Price | |
---|---|---|---|---|
<%=h order_item.product.name %> | <%= text_field_tag 'quantity[]', order_item.quantity %> <%#= order_item.quantity %> | <%= number_to_currency(order_item.unit_price) %> | <%= number_to_currency(order_item.full_price) %> | <%= link_to 'Remove', order_item, :confirm => 'Are you sure?', :method => :delete %> |
Total: <%= number_to_currency @order.total_price %> |
<%= submit_tag “Update” %>
<% end %>
By the way, the params[:ids] is a hidden field in the cart view.
Basically what I need to do is find a way to create an array of hashes
where the key is the quantity field and the value is in the
params[:quantity] for the appropriate id. The above code works although
it is obviously hard coded.
I was thinking something like this may work:
for i in params[:quantity]
qtys = {‘quantity’ => i}
end
But it doesn’t…
Also - I can’t help to feel this is bad approach. There must be a
cleaner way to update the multiple quantity records without having to do
this, right?
Any input would be GREATLY appreciated! Let me know if something is
unclear or if you have any questions! Thanks!
-Tony