ankane / authtrail

Track Devise login activity

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Idea: keep N most recent logins

vlad-pisanov opened this issue · comments

great gem! it would be cool if it also had a built-in mechanism for purging old records:

i.e. a global setting that either keeps:

  • N most recent logins per user/identity, or
  • N days worth of login history

Hey @vlad-pisanov, thanks for the suggestion! Added a "Data Retention" section to the readme in the commit above. Since it's fairly straightforward with Active Record, I'm not sure additional functionality is needed.

I ended up with this solution to keep the 10 latest entries per user:

class LoginActivity < ApplicationRecord
  after_commit :purge_old_logins!, on: :create

  private

  def purge_old_logins!
    user_scope = self.class.where(user: user)
    latest_ids = user_scope.order(created_at: :desc).limit(10)
    user_scope.where.not(id: latest_ids).delete_all
  end
end

Great, thanks for sharing. Should be useful to others who want to do the same (also, you may want to skip if no user is set).