Destroying a Rails 3 object in a rake?

I am stuck in a simple problem here. I am creating an application that manages a database of coupons, each of which has an expiration date. I am trying to create a rake task that will remove expired coupons. The corresponding code from the rake file is as follows:

desc "Deletes expired offers from the database." task :purge_expired => :environment do today = Date.today.to_s Offer.where('expires_on < ?', today).destroy end 

Something fails with the following error message:

 rake aborted! wrong number of arguments (0 for 1) 

I just don’t know why. What arguments are needed?

As an experiment, I found this works fine:

 desc "Deletes expired offers from the database." task :purge_expired => :environment do today = Date.today.to_s puts Offer.where('expires_on < ?', today).count end 

This returned the correct number of records, so I assume that I am successfully collecting the necessary objects.

FWIW, I tried this too, and I had no luck:

 desc "Deletes expired offers from the database." task :purge_expired => :environment do today = Date.today.to_s @offers = Offer.where('expires_on < ?', today) @offers.destroy end 

So, I'm a little out of ideas. What am I doing wrong here?

Many thanks for your help. I’m sure I wouldn’t have a job if not for Stack Overflow!

0
source share
2 answers

You're close You just need to use #destroy_all instead of #destroy . The latter requires an id argument.

 today = Date.today.to_s Offer.where('expires_on < ?', today).destroy_all 
+1
source

First of all, to debug things from a rake, call it with the --trace option. Your problem here is not specific to rake.

Offer.where('expires_on < ?', today) is going to return the collection, not one instance of Offer , and there is no destroy method for the collection.

You can iterate over each expired sentence and call destroy . Something like that:

 @offers = Offer.where('expires_on < ?', today) @offers.each { |offer| offer.destroy } 
+1
source

All Articles