How do I allow multiple shopping carts per user?

I’m creating an order entry application based on the depot application
in Dave Thomas’s book “Agile Web Development with Rails”, except one
major difference is that I want the user to be allowed to have any
number of orders open at a time. The idea is that a sales
representative will, in the process of creating an order, drag and drop
any number of line_items onto the order and using AJAX the items on the
order will be updated. At this point, the order has not yet been saved
so I’m storing the line_items in a session variable. However, when I have two orders open at the same time the session variable gets applied to both orders, and any
items added to one order are also added to the other.

That said, I need to find an alternative solution and I’m
wondering what would be the best way to do this? I’m hoping there’s a
more elegant solution than updating a hidden input in the form. Any suggestions would be appreciated.


PS The AJAX code was taken from the shopping cart demo on

If you want to keep cart and item info in the session as you
currently have it, you can just change the cart item in the session
hash to an array, so you could have an array of carts, each with its
own set of items.

Ben, thanks for your quick response.

But how do I tell the carts apart? How would I make sure the correct cart ends up with the correct order since the orders don’t have any unique ID yet? I’m not set on storing the item info in the session if there’s a good alternative.

It sounds like maybe I need to give each order a unique identifier before the user adds any items or saves the order, and that way I can use your suggestion and create a hash of carts with the order id as the key.

So would you recommend that I have a value stored in the database that increments every time an order is started but before it’s saved or and lines are added to it? I could store that id in a hidden input and then use the value when I create the order. And if I do this, how would I change the “drop_receiving_element” to pass the ID along with the product_id? Am I going to need to add a hidden input containing the order_id to each of my Draggables?

Thanks in advance for the help. I’m just beginning to learn Ruby and Rails, but I’m sure enjoying it!

You could store the carts as a hash, keyed by a token or GUID. I
personally put carts in the database so I get full ActiveRecord
richness for them (and then convert them to a sale and then a
shipment later), but some people prefer not to have that kind of
transient data in the database.