views:

30

answers:

2

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?

+2  A: 

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 complete 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.

Simone Carletti
I think this is the way to go. Conceptually, it makes sense to me to use the model. Temporary, not-yet-valid data should not be in the database, right? As a practical matter, though, I can see that it doesn't make sense and that this type of solution will be more robust. Thanks for your input.
tacomachine
A: 

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.

EmFi
Yes, I think this is the way to go if you must use the session. What I had also considered was to store partial records in the database, but only associate them to the user via the session using a hash relating the respective user_id to the id of the partial record. I believe this would work, but it is relying on the session unnecessarily. Simone's solution should do the same thing, but better.
tacomachine