Reputation: 4853
I have a Ruby on Rails model that has a column called expiration_date
. Once the expiration date is reached, I want another column on the model to be modified (e.g. expired = true
). What are some good ways of doing this?
Ideally I'd like a model function to be called at the exact moment the expiry date is reached.
Upvotes: 6
Views: 2147
Reputation: 64373
Use delayed_job
gem. After installing delayed_job gem do the following:
class Model < ActiveRecord::Base
after_create :set_expiry_timer
# register the timer
def set_expiry_timer
delay(:run_at => expiration_date).expire
end
def expire
update_attribute(:expired, true) unless expired?
end
end
Upvotes: 6
Reputation: 1529
Have you considered using a scheduler to automate this? Something like Resque, Delayed Job or Cron would work fine.
Then in your scheduled task you could have something like this:
if foo.expiration_date < Time.now
foo.is_expired = true
foo.save
end
Upvotes: 0
Reputation: 18550
For the scenario you describe, the best solution is to have an expired
method instead of a column, that would return true iff the expiration_date
is greater or equal than the current date.
For other scenarios, I would go with a DB scheduled event triggering a stored procedure. That procedure would check the expiration_date
column for all the rows in the model table, and update the expired
(or other(s)) column(s) accordingly.
Upvotes: 2