说明如何在记录三个月前运行方法



基本上我想做的是删除一个文件和一个记录(其中包含文件路径),当记录三个月时,文件通过Carrierwave上传。

这是我删除记录和文件的想法。

 # Code for deleteing PDF files (receipts) every 90 days
  def auto_delete_receipts
    #get user id from params or as a method parameter
    user = params[:id]
    user.receipts.each do |receipt|
      #check if receipt is three months old
        receipt.remove_receiptFile!
        receipt.save
      #end
    end
  end

所以我想知道我应该在哪里找到我的方法,以及如何在每次记录三个月前自动运行它,以便删除它。

感谢您的阅读。

你从错误的角度看它。与其创建将在三个月后触发的单个回调,不如创建一个定期运行的任务并修剪超过特定期限的记录。

反过来做不会很有效率,因为你需要跟踪什么时候应该触发所有这些回调,并且你必须在每条记录的基础上进行。

第一步是创建一个耙子任务:

namespace :things do
  desc "Removes records older than 3 months"
  task :prune => :environment do
    puts "Removing things older than 3 months"
    destroyed = Thing.where("created_at < ?", 3.months.ago).destroy_all
    puts "{destroyed.length} records deleted."
  end
end

如果您正在部署到支持 cron 的服务器,注释中提到的 whenever gem 是安排此操作的好方法。在 Heroku 上,您可以使用调度程序代替,这是一个插件。

您走在正确的轨道上,我建议您创建一个脚本,成功识别并删除 90+ 天前的 PDF。然后你可以利用 cron 每天运行脚本。

您的示例使用方法 each - 实际上主要用于数组,您最好使用像@max建议的答案这样的 rake 任务 - 您可以在此处阅读更多内容:http://ruby-doc.org/stdlib-2.0.0/libdoc/rake/rdoc/Rake/Task.html

要了解cron,您可以在此处阅读更多内容:我不知道您使用的服务器,但假设它是一个 Linux 实例,这里有一个来自 Amazon 的有用指南:http://docs.aws.amazon.com/opsworks/latest/userguide/workingcookbook-extend-cron.html

最新更新