My Rails app allows administrators to give other players infractions, which are stored in a database table. These infractions have point values that add up to give the player a points value. However, these records will contain an expiry time stamp. Is there any way of automatically deleting the infraction record when the expiry date has been reached?
Asked
Active
Viewed 1,854 times
4
-
You can run a periodic cron job that will delete expired records. – Sergio Tulentsev Nov 16 '13 at 17:31
-
Or use a Rails-based scheduler. I'm surprised that searching the web for this functionality didn't yield any results. – Dave Newton Nov 16 '13 at 17:32
1 Answers
5
How about using a default scope that filters out expired records? Something like
class Infraction < ActiveRecord::Base
default_scope -> { where("expired_at IS NULL OR expired_at < ?", Time.now) }
before_create :set_expired_at
private
def set_expired_at
self.expired_at = Time.now + 1.week
end
end
This way, you can do Infraction.find(4)
, and if the infraction with id == 4 is expired, it won't be returned.

Adam Becker
- 353
- 2
- 10
-
This is a good idea, but it doesnt really answer my question. I'm going to have to delete other records automatically in the future, and was hoping I could get something implemented now to deal with this, and I rather not have unnecessary records clogging up my database. – Melvin Sowah Nov 17 '13 at 10:33
-
Ah, ok. In that case, you need to run a background worker or cron job. – Adam Becker Nov 24 '13 at 19:01
-
This answer in combination with the cron job could be a good solution to keep the database clean and also to have more accurate results if you need expire times to be highly accurate. I also was just reading about Redis which has expire values and Redis handles deleting expired records automatically. I think I'm going to try this the next time I need this feature. – Kevin Jan 22 '18 at 19:31