Erase records every 60 days

£可爱£侵袭症+ 提交于 2019-11-27 16:39:55

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/13975376/erase-records-every-60-days

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