Storing Objects in a Session in Rails

Solution 1:

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 :)

Solution 2:

Rails tends to encourage RESTful design, and using sessions isn't very RESTful. I'd probably make a Quiz resource that has a bunch of words, as well as a current_word. This way, when they come back, you'll know where they were.

Now, REST isn't everything (depending on who you talk to), but there's a pretty good case against large sessions. Remember that sessions write things to and from disk, and the more data that you're writing, the longer it takes to read back...

Solution 3:

Since your app is a Rails app, I would suggest either:

  1. Using your clients' ability to cache by caching the cards in javascript. (you'd need a fairly ajaxy app to do this, see the latest RailsCast for some interesting points on javascript page caching)
  2. Use one of the many other rails-supported server-side caching options (i.e. MemCached) to cache this data.