Reputation: 680
I am making a auction web app. When a ad is created, I automatically add expiration date into database.
before_create :set_expiration_date
def set_expiration_date
self.expiration_date = Time.now + 60.days
end
How can I add a background task/job, so when a ad has reached its expiration date, it can change the status to false
.
Is it any good gem that I could use in my case?
I have tried whenever gem and it was very cumbersome and it didn't ran in background and hard to understand.
Upvotes: 1
Views: 1077
Reputation: 97
I do not have enough information to be sure, but keep the system updating records sounds a little overcoding for me. Is really necessary to store your model status
field? I mean, you can also calculate if your records have expired whenever you need it and only when you need it, just add a scope
to your model like:
class Food < ApplicationRecord
scope :not_expired, -> { where(:expiration_date > DateTime.now) }
end
Then you used it like this:
@groceries = Food.not_expired
Upvotes: 1
Reputation: 447
Just create background job changing the status in after create callback which would be performed at exp. date
more info: http://guides.rubyonrails.org/active_job_basics.html
Upvotes: 0
Reputation: 4443
In your lib/tasks file, create a file called something.rake
and inside that file, create a task by saying:
task :name_of_task => :environment do
# name of model
Ad.find_each do |ad|
# if add expired, change status to false and save
end
end
You can run your task by saying rake name_of_task
in the terminal...or you can add name_of_task
to the heroku scheduler if you're using heroku. https://elements.heroku.com/addons/scheduler
Upvotes: 0