4

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?

Melvin Sowah
  • 700
  • 1
  • 10
  • 29

1 Answers1

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