Isnor Creative
Isnor Creative Blog
Ruby, Ruby on Rails, Ember, Elm, Phoenix, Elixir, React, Vue

Jul 6, 2010

Deleting Old Ruby on Rails Active Record Sessions Using Whenever and Capistrano

If you’re using the Rails Active Record session store, you’ll notice that it does not delete old sessions. I’ve found this can quickly lead to sessions tables bloated with 100,000 records. I found a good solution on a blog for this, but it required some extra work to get this running with the whenever gem in my Webfaction environment.

  1. ## First of all this depends on having the javan whenever gem installed:
  2. ## Capistrano

I’m also assuming you are using Capistrano, throw this in your config/deploy.rb file. You’ll want to modify the path to your copy of whenever. Note that I have this setup to write a new crontab with each deploy.

  1. ## Deleting The Expired Sessions

The meat and drink of the solution relies on the following one liner, put it in app/lib/delete_expired_sessions.rb:

  1. ## The Whenever Schedule:

Now add a cron job in your whenever schedule located at config/schedule.rb, again you’ll want to modify the paths to your app and your copy of Ruby:

  1. ## Verify That It’s Working

Maybe I did this the lazy way, but hey, it works: by temporarily set the cron job to run every 5 minutes and then check the database to make sure the number of sesssions has dropped dramatically. Don’t forget to reset the cron job to run as infrequently as you want.


I am available for Ruby on Rails consulting work – get in touch to learn more.

Gordon B. Isnor

Gordon B. Isnor writes about Ruby on Rails, Ember.js, Elm, Elixir, Phoenix, React, Vue and the web.
If you enjoyed this article, you may be interested in the occasional newsletter.

I am now available for project work. I have availability to build greenfield sites and applications, to maintain and update/upgrade existing applications, team augmentation. I offer website/web application assessment packages that can help with SEO/security/performance/accessibility and best practices. Let’s talk

comments powered by Disqus