Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How/where to temporarily store ActiveRecord objects if not in session?

I'm refactoring a Rails-based event registration application that has a checkout process that hits several ActiveRecord models. Ideally, the objects should not be saved unless checkout is complete (payment is successfully processed). I'm not entirely certain why it would be a bad thing to serialize these objects into the session temporarily, but I've read over and over that its bad mojo. At least there's no risk of getting out of sync with existing records, as there won't be any existing records.

My questions are:

A) Is it still problematic to store records in the session even though they don't exist elsewhere? Even if I modify a model, can't I kill all existing sessions?

B) If it may cause problems, how should I temporarily store objects? Should I save them and use a boolean flag to indicate permanent vs. temporary status? Then cron a script to weed out stale temporary objects?

Thoughts?

like image 789
tacomachine Avatar asked Feb 20 '10 08:02

tacomachine


2 Answers

Why don't you store them in the database, but in a way you know they are "incomplete"?

For example, you can add a added_to_cart_at datetime field. When the product is added to the cart, you save the record and you set the value for that field. Then, if the user completes the purchase, you clear the field and you associate the product to an order.

To clear stale record, you can setup a daily cron to delete all records where added_to_cart_at is older than 1.day.ago.

like image 189
Simone Carletti Avatar answered Sep 27 '22 22:09

Simone Carletti


The problem of storing them in the session is that the session has limited space. ActiveRecord objects bring a lot of overhead in terms of space when stored in the session. If you're storing records with densely populated has_many relationships you will run into trouble.

I believe Simone Carletti's description of storing partial records in the database to be the best solution.

But, if you really want to store objects in the session, store the minimum amount of information possible. For example ids and updated fields only. Also store the information as a hash, instead of storing the object in the session directly.

like image 43
EmFi Avatar answered Sep 27 '22 22:09

EmFi