Idea: keep N most recent logins
vlad-pisanov opened this issue · comments
Vlad Pisanov commented
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
Andrew Kane commented
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.
Vlad Pisanov commented
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
Andrew Kane commented
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).