Erase records every 60 days

时光怂恿深爱的人放手 提交于 2019-11-29 02:21:30
Unixmonkey

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.

dimuch

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!