Storing ActiveRecord objects in session?


Is it safe to store ActiveRecord objects in a session? I want to avoid too
much overhead.
Perhaps storing the object id would suffice too, but is that safe?


Yes, you can store whole objects (as long as they can be marshaled). The
potential pitfall is that, if your model changes, then you'll have old
instantiations of the model that don't match the current, which
depending on the model and changes, may not be a problem, or it might be
disastrous. There are ways to deal with this, including wiping out all
the sessions when you deploy a new version with those model changes, but
that may not be desirable either.

Yes, you can also store just the object id. For most purposes, that's
what I prefer to do these days. YMMV

Bart Braem wrote:

Keep in mind that sessions are stored either as temp session files or
in a database.

I don't think you'll save much in terms of performance as you are
either pulling the data from the session file on the web server or
pulling it from the session database. My assumption is that the same
cost in performance would occur whether you are actively pulling it
from the DB every time or calling on a session object which is stored
in the DB.

A session is good for maintaining a constant state throughout an app,
but shouldn't be confused with caching.

Actually yes you should only store model id atrributes and simple string or numeric values in the session. Its a common misconception that the session should be the same speed as the database. It is not. If you store model objects in the sessions they can get stale and also these objects have to be marshalled and unmarshalled from the session on each hit after they are pulled from the filesystem or db. So it is better performance to store an id and do a loohup in the db to get it back when you need it. Don't store model objects in the session, you should try to store as little as possible to maintain the state you need but no more.


Ezra has a good point about speed and efficiency but if that’s not the issue then yeah you can save them in the session, albeit with a very important caveat:

The whole AR model is not guarenteed to be saved in the session, just the type and id. The rest of the record can and will disappear and has to be pulled again from the database when needed. Thus, you cannot store unsaved AR objects in the session, for reasons of serializability (AR objects basically can’t be serialized in and of themselves). So you have to be careful about AR objects in the session, but yes it is possible.


Bart Braem wrote:

Is it safe to store ActiveRecord objects in a session? I want to avoid too
much overhead.

Thanks for your reactions, I'm not going to store the AR objects in the
session. You've warned me enough...