Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erase records every 60 days

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.

like image 301
Jean Avatar asked Dec 20 '12 15:12

Jean


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 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.

like image 117
Unixmonkey Avatar answered Nov 04 '22 03:11

Unixmonkey


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.

like image 31
Natus Drew Avatar answered Nov 04 '22 03:11

Natus Drew


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.

like image 42
dimuch Avatar answered Nov 04 '22 03:11

dimuch