Storing Objects in a Session in Rails

The main reason not to store objects in the session is that if the object structure changes, you will get an exception. Consider the following:

class Foo
  attr_accessor :bar
end

class Bar
end

foo = Foo.new
foo.bar = Bar.new
put_in_session(foo)

Then, in a subsequent release of the project, you change Bar’s name. You reboot the server, and try to grab foo out of the session. When it tries to deserialize, it fails to find Bar and explodes.

It might seem like it would be easy to avoid this pitfall, but in practice, I’ve seen it bite a number of people. This is just because serializing an object can sometimes take more along with it than is immediately apparent (this sort of thing is supposed to be transparent) and unless you have rigorous rules about this, things will tend to get flummoxed up.

The reason it’s normally frowned upon is that it’s extremely common for this to bite people in ActiveRecord, since it’s quite common for the structure of your app to shift over time, and sessions can be deserialized a week or longer after they were originally created.

If you understand all that and are willing to put in the energy to be sure that your model does not change and is not serializing anything extra, you’re probably fine. But be careful 🙂

Leave a Comment