I need to erase records in my offers models if the record has more that 60 days from the created_at date.
I only found information about how to populate my model with a rake task, but I couldn't find information about how to make a rake task to delete records. So I just wonder if I have to do this with a task or if rails has something else to do this.
Create a file for the task:
# lib/tasks/delete_old_records.rake
namespace :delete do
desc 'Delete records older than 60 days'
task :old_records => :environment do
Model.where('created_at < ?', 60.days.ago).each do |model|
model.destroy
end
# or Model.delete_all('created_at < ?', 60.days.ago) if you don't need callbacks
end
end
Run with:
RAILS_ENV=production rake delete:old_records
Schedule it to run with cron (every day at 8am in this example):
0 8 * * * /bin/bash -l -c 'cd /my/project/releases/current && RAILS_ENV=production rake delete:old_records 2>&1'
You can also use the whenever gem to create and manage your crontab on deploys:
every 1.day, :at => '8:00 am' do
rake "delete:old_records"
end
Learn more about the gem on Github.
60.days.ago generates a timestamp like
Fri, 08 Aug 2014 15:57:18 UTC +00:00
So you'd need to use < to look for records older(less) than the timestamp.
Online.delete_all("created_at < '#{60.days.ago}'")
It's just a slight oversight by Unixmonkey. I'd also use the delete_all instead of looping each iterating in a block.
You can create a rake task to delete expired offers , or create class method for your offers model and call it using, for example, whenever gem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With