5

How does Rails know when to delete a record from the sessions table?

For example, if a user visits the website, a session record is created, but when the user closes the browser window, the server doesn't get any notification, so how does Rails delete records from sessions table?

Zabba
  • 64,285
  • 47
  • 179
  • 207

2 Answers2

7

There are simplier ways:

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

You can call it after some Action in Controller and this piece of code kill all dead sessions.

Of course it is disputable technique, but the simplest.

Full story

Dzmitry
  • 436
  • 6
  • 13
  • 1
    I'd really want to do something like that asynchronously, like from a cronjob. – Dogweather Apr 24 '12 at 02:39
  • 1
    This worked well, run through rails runner along with whenever gem to make it as a cron job. – Rystraum Sep 25 '12 at 07:25
  • We had a similar problem and wanted to get away from running this via cron, so we're experimenting with MySQL Events: http://dev.mysql.com/doc/refman/5.5/en/create-event.html. Hopefully that helps others running into the same thing. – Chip Castle Mar 04 '13 at 18:08
  • Here is the updated "Full Story" link regard using a datastore as a disputable technique. http://www.isnorcreative.com/blog/deleting-old-ruby-on-rails-active-record-sessions-using-whenever-and-capistrano We use database storage for sessions when working with multiple web servers. It is a good solution as long as you keep stale sessions purged, otherwise, it bloats horribly. – scarver2 Jul 20 '13 at 13:11
3

You have to provide your own implementation of session expiration, to my understanding.

This API page gives you a pretty decent answer to how that works. You create your database table with the extra attributes created_on and updated_at (and you get timestamps for free) and then you just create a job to expire them whenever you want by looking at the updated_at attribute.

This post has details of how to run a job.

Community
  • 1
  • 1
Christopher WJ Rueber
  • 2,141
  • 15
  • 22