0

I tried to a records cleanup after certain period of time (6 month) using gem 'whenever'.

In my whenever scheduler :

every 1.month, at: '1am' do
  rake 'lib/tasks/cleanup_user.rake'
end

In the lib/tasks/cleanup_user.rake

@user = User.all.where(:created_at > 'Time.6.month.ago').delete

It seems about right. However, I got error 'uninitialized constant User'. I am relatively new in rails. Please assist me.

EDIT : I changed the game by run clean one line command :

set :output, "log/cron.log"
    every 1.minutes, :environment => :development do
      command 'User.where("confirmed = 0 AND created_at <= ?", 6.months.ago).delete'
    end

I set the specific environment,and run this in command :

whenever --set environment=development --update-crontab userscleaning

Checking at crontab, its there but still not work. Any thought?

Firdaus Adib
  • 11
  • 1
  • 3

2 Answers2

0

Try adding the environment dependency to your task.

task :cleanup_users => :environment do
  User.where(:created_at > 'Time.6.month.ago').delete_all
end

If you want the callbacks to trigger, use destroy_all

task :cleanup_users => :environment do
  User.where(:created_at > 'Time.6.month.ago').destroy_all
end

Here is a relevant Railscasts.

HungryCoder
  • 7,506
  • 1
  • 38
  • 51
  • Hi Hungry coder, I tried that. Its not work too. However, I changed to a cleaner way at above. Hope you can have a look. – Firdaus Adib Mar 31 '13 at 11:43
0

According to the answers here:

# lib/tasks/delete_old_records.rake
namespace :delete do
  desc 'Delete records older than 6 months'
  task old_records: :environment do
    User.where('created_at > ?', 6.month.ago).destroy_all
  end
end

Run with:

RAILS_ENV=production rake delete:old_records

In whenever:

every 1.minutes do
  rake "delete:old_records"
end

Or in cron:

0 8 * * * /bin/bash -l -c 'cd /my/project/releases/current && RAILS_ENV=production rake delete:old_records 2>&1'
asvetly
  • 1,739
  • 16
  • 17