Erase records every 60 days

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.