views:

269

answers:

3

Hi I have a problem implementing add to cart functionality in my rails e-commerce app. Here I am not talking about check out function. Just "add to cart". Items can be added to cart without requiring users to log in to their accounts. Once the user finishes adding to cart, then before check out user will log in. My problem here is what is the best way to store those items added to the cart. I am trying to use session. I can easily implement this if the user adds to cart JUST one product with any quantity. But how to store the information temporarily if user checks out multiple items with different quantities. I need a data structure to store this information but don't know which data structure to use. I mean something like this:

Session_id | product_id | quantity
wisidiri4i | 1234       | 3    
349sksksks | 3452       | 6

And so on.....

Using hash I can store one item, but how to store multiple items?? Using DB table, I can do this but how to delete those records from the table if user leaves with items added to cart but without check out?

I am stuck here. Any help would be appreciated. Thanks

+1  A: 

Agile Web Development with Rails has sample code for this.

JRL
A: 

In general, you should use the session ID along with a database to store the product(s). This keeps the session information minimal (just the ID) and provides you with the most flexibility. IMO its a bad idea to put a data structure like this into the session store: what if you decide to change the data structure later? You'd have to support both the old and new versions of the data structure.

As you noted, the problem with a db-based solution is that at some point you need to clear out the unpurchased items from the database. This is typically done periodically (eg. carts over X days old are purged), where the timeframe can be based on the size of the database (how big does it grow if carts are purged after 3 months? 6 months) and whether people are likely to return at some point in the future (will they return 3 months later? 6 months?).

If you decide to store the info in the session, then you'd probably want to do some type of simple serialization, eg:

Session_id  |  Items
892jsls098s |  sku1:3,sku2:4,sku3:2

The only limitation here is how long the session data can be (definitely add a length check).

Pete Campbell
A: 

Hi Pete, Thanks for the suggestion. Both the ideas you suggested are good. Can you tell me one thing? If I want to use session, how can I implement the data structure you suggested above (892jsls098s | sku1:3,sku2:4,sku3:2) and how to implement the serialization? If possible, can you provide me a sample code? Is that Hash what you suggested me to use? I appreciate your help.

Rup