Maintenance Tasks

Removing Sessions from the Database

If you configured Rails to store browser sessions in the database, it is recommended to remove them regularly in order to prevent the table concerned from becoming too large and thus impairing overall performance.

For this, you can use the following Ruby code as a rake task in your project. This task can and should be run regularly as a cron job.

namespace :db do
  namespace :sessions do
    desc "Prune database-stored sessions older than one week"
    task :prune => :environment do
      CGI::Session::ActiveRecordStore::Session.delete_all ["updated_at < ?", 1.week.ago ]
    end

    desc "Count database sessions"
    task :count => :environment do
      puts "Currently storing #{CGI::Session::ActiveRecordStore::Session.count} sessions"
    end
  end
end