Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
957 views
in Technique[技术] by (71.8m points)

ruby on rails - Erase records every 60 days

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...