Reputation: 21513
How to delete
an object certain times later after it is created
?
I thought it would be something like? But how can I schedule this action?
after_create :destroy_essay
def destroy_essay
# 10minutes later
# self.destroy
end
Upvotes: 1
Views: 1737
Reputation: 199
@methyl I think a correct scope would be scope :expired, -> { where('created_at <= ?', 10.minutes.ago) }
, wouldn't it?
Upvotes: 0
Reputation: 3312
You should probably write rake task for this, and use cron, or if you are on Heroku, Heroku Scheduler to run it.
Add a scope in model, like expired
, which returns all items older than 10 minutes, then in rake task do Essay.expired.destroy_all
and run this task, for example every one minute.
This rake can look like this:
namespace :app do
desc "Remove expired essays"
task :remove_expired_essays => :environment do
Essay.expired.destroy_all
end
end
and the scope in your model:
scope :expired, -> { where('created_at >= ?', 10.minutes.ago) }
Upvotes: 0
Reputation: 19789
This is actually a perfect job for a background worker. I'd definitely recommend using Sidekiq
It even provides a way to perform a job after a certain amount of time in the future. https://github.com/mperham/sidekiq/wiki/Scheduled-Jobs
EssayDestroyer.perform_at(10.minutes.from_now)
On your EssayDestroyer
worker you'd then write the code to execute to destroy the essay that you created.
Upvotes: 1