Calling a model method at a specific time (Ruby on Rails)

I have a Ruby on Rails model that has a column with a name expiration_date. Upon reaching the expiration date, I want to change another column on the model (for example, expired = true). What are some good ways to do this?

Ideally, I would like the model function to be called when the expiration date has been reached.

+5
source share
3 answers

In the described scenario, the best solution is a method expiredinstead of a column that returns true if expiration_dategreater than or equal to the current one.

DB, . expiration_date expired ( ).

+2

delayed_job gem. delayed_job :

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
+5

Have you considered using a scheduler to automate this? Something like Resque , Delayed Job, or Cron will work fine.

Then in your scheduled task, you can do something like this:

if foo.expiration_date < Time.now
  foo.is_expired = true
  foo.save
end
0
source

All Articles