每 60 天清除一次记录 [英] Erase records every 60 days

查看:50
本文介绍了每 60 天清除一次记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果记录距 created_at 日期超过 60 天,我需要删除优惠模型中的记录.

I need to erase records in my offers models if the record has more that 60 days from the created_at date.

我只找到了有关如何使用 rake 任务填充模型的信息,但找不到有关如何执行 rake 任务以删除记录的信息.所以我只是想知道我是否必须通过任务来执行此操作,或者 rails 是否还有其他功能可以执行此操作.

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.

推荐答案

为任务创建文件:

# 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

运行:

RAILS_ENV=production rake delete:old_records

安排它与 cron 一起运行(在这个例子中每天早上 8 点):

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'

您还可以使用 whenever gem 在部署时创建和管理您的 crontab:

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

Github 上了解有关 gem 的更多信息.

Learn more about the gem on Github.

这篇关于每 60 天清除一次记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆