So here it is the update to tell you how to remove old sessions from your database. How did those sessions get into your database in the first place? For the answer to that question check out my previous post entitled "Initialized! good, Authorized? Great!".
Now that we all know that Ruby on Rails does not clear old sessions for us (surprising since it does just about everything else you would ever want it to do), we have to take care of the session overload. I have went over a week without clearing my sessions, and on this small site those records started to pile up. So how did I take care of it?
I decided that staying away from some seperate script and cron job would ultimately prove the best solution. By keeping all the session management inside my RoR application I prepare it for any move to any other system. Besides, clearing the sessions is quite easy. Below is the SQL statement necessary to remove old sessions:
DELETE FROM sessions WHERE now() - updated_at > 3600;
Simple enough. The number 3600 is of course the time in seconds (in this case 2hrs). So when should we run this statement? - every 30 minutes, hour, 2 hours? I would suggest for the sake of simplicity, and for strict adherence to your session policy:
Sessions should be cleared each time the controller is called, before any session is checked for or created.
Makes sense, we certainly don't want sessions being accepted after our set timelimit for the sake of good policy. So what must we do to make this happen?
Ruby on Rails makes it easy to call a function before any other action is taken. So I decided to take my SQL call and put into a function called "kill_sessions" (sounds serious!). Then at the top my controller that is worried about sessions I placed the instruction:
before_filter :kill_sessions
The only problem I ran into was trying to get my simple SQL statement to just execute. I tried the basic "execute()" command I found in the Rails API. However I couldn't get it to work. Luckily I stumbled across this requirement while googling the problem:
To use the execute method you must write it like so:
ActiveRecord::Base.connection.execute()
A bit annoying if you ask me. Perhaps I'll find an easier way of doing it later, but hey, thats what learning a new language / framework is all about. Learn as you go. =)
