October 28, 2006

Grafting Rails Into an Existing Website: Sessions

I learned something interesting the other day about using sessions with multiple rails apps: be careful with storing models in sessions. Or, to put it another way, don't store models in sessions. Well, you could, but you'd have to make sure that the model was included in each of your apps. This is, of course, entirely possible, but we're not doing it currently, and thus we get this:


  1. Store model in session in App #1, e.g., session[:user] = User.find(15).

  2. In a browser, navigate from App #1 to App #2, lacking the User model.

  3. Watch App #2 throw an error.


So, for the time being, we're going to only store non-model data in the session. For example, we could use session[:user_id] = 15, then create a local instance variable of the model. Or, if there are a few common things that'll be used, create things like session[:user_firstname] or session[:user_email]. This should ensure less random carnage due to model mismatches.