Don't Abuse the Session

Never, ever, ever, ever, ever store an ActiveRecord model in the session. Just store the id and load it into an instance variable from the database on every request. Why? A couple reasons...

First, you're susceptible to staleness. Consider this. User A logs in, and you store their user object in the session. Administrator X logs in and deactivates User A's account. User A can still muck around your site because you're reading the user data from the session, which has stale data.

Second, the default in Rails these days is to store your session data in cookies (honestly, I don't know why.....it only clutters up your requests, forcing the session to be passed back and forth on _every_ request, and opening up the possibility that the encryption key could be brute-forced......this is a rant for another day). You just don't want to be storing whole ActiveRecord objects in the session. They're big and clunky. The extra database call to reload the object in a before_filter on every request is practically trivial, and you'll keep the "tubes" less clogged.

This practice is certainly not rails-specific, and should be adopted no matter the server-side technology.

comments powered by Disqus