Erase entries every 60 days

I need to erase entries in the models of my sentences if the entry has more than 60 days from the date created_at.

I only found information on how to populate my model using the rake function, but I could not find information on how to make the rake task to delete records. So I just wonder if I need to do this with the assignment or if the rails have something else to do.

+4
source share
3 answers

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 cron (every day at 8:00 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][1] stone to create and manage your crontab during deployment:

 every 1.day, :at => '8:00 am' do rake "delete:old_records" end 
+11
source

60.days.ago creates a timestamp like

 Fri, 08 Aug 2014 15:57:18 UTC +00:00 

So, you will need to use <to search for records older (less) than the timestamp.

 Online.delete_all("created_at < '#{60.days.ago}'") 

This is just a little Unixmonkey supervision. I would also use delete_all instead of looping every iteration in a block.

+8
source

You can create a rake task to delete expired sentences or create a class method for your proposal model and call it using, for example, whenever gem.

+3
source

All Articles