开发者

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

开发者 https://www.devze.com 2022-12-21 04:43 出处:网络
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 (pa

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 (pa开发者_JAVA百科yment 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消