How to clear rails sessions table

2020-02-08 15:30发布

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?

4条回答
何必那么认真
2楼-- · 2020-02-08 15:38

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])
查看更多
Bombasti
3楼-- · 2020-02-08 15:43

When you call reset_session rails will delete that row from the session table. However not every session will have reset_session called on it: if a user closes their browser without logging out then the browser will discard the session cookie, so that session row will never be used again, but reset_session won't be called.

Rails won't clear out that accumulating cruft for you - it's up to you to do any housekeeping on it as you see fit. In a previous job we use to run a cronjob that deleted old session rows.

查看更多
走好不送
4楼-- · 2020-02-08 15:54

I would recommend clearing your rails sessions using a cron job or something. Maybe not 24 hours tho, depends on how long you want user sessions available for. Rails provides a rake task for this

rake db:sessions:clear

查看更多
▲ chillily
5楼-- · 2020-02-08 15:57

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.

查看更多
登录 后发表回答