Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear rails sessions table

I use active record store for rails sessions store.

Over just a short time, the size of sessions table has increased a lot. How are these session rows dumped after a certain period of time. Or should I manually clear them once in 24 hours?

like image 622
Anand Avatar asked Apr 10 '12 12:04

Anand


People also ask

How do I delete a session in rails?

To clear the whole thing use the reset_session method in a controller. Resets the session by clearing out all the objects stored within and initializing a new session object.

Where are sessions stored in rails?

Rails store it in server side. Session is saved in server side like key value pair (like json object)

How does session work in Rails?

Rails provides a session object for each user that accesses the application. If the user already has an active session, Rails uses the existing session. Otherwise a new session is created. Read more about sessions and how to use them in Action Controller Overview Guide.


2 Answers

Use a standard call to ActiveRecord in Rails 3.2. For the date, pass a value that matches the length of your "Remember me" duration. In my example, this will clear ALL sessions that have been inactive for two weeks.

ActiveRecord::SessionStore::Session.delete_all(["updated_at < ?", 2.weeks.ago])

As stated by @journeyer below, if using the Devise gem, one can reference the Devise' configuration.

ActiveRecord::SessionStore::Session.delete_all(["updated_at < ?", Devise.remember_for.ago])

If using the Sorcery gem, one can reference the Sorcery's configuration.

ActiveRecord::SessionStore::Session.delete_all(["updated_at < ?", User.sorcery_config.remember_me_for.ago])
like image 113
scarver2 Avatar answered Oct 17 '22 03:10

scarver2


A good blog post about your issue : http://blog.brightbox.co.uk/posts/clearing-out-rails-sessions

The solution is to create a custom rake task:

task :clear_expired_sessions => :environment do
    sql = 'DELETE FROM sessions WHERE updated_at < DATE_SUB(NOW(), INTERVAL 1 DAY);'
    ActiveRecord::Base.connection.execute(sql)
end

... and run it every day with a cron job.

like image 23
Thomas Guillory Avatar answered Oct 17 '22 03:10

Thomas Guillory