在 rake 中销毁 Rails 3 对象? [英] Destroying a Rails 3 object in rake?

查看:32
本文介绍了在 rake 中销毁 Rails 3 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里遇到了一个简单的问题.我正在构建一个管理优惠券数据库的应用程序,每个优惠券都有一个到期日期.我正在尝试构建一个将删除过期优惠券的佣金任务.rakefile 中的相关代码如下所示:

I'm stuck on a simple issue here. I'm building an application that manages a database of coupons, each of which has an expiration date. I'm trying to build a rake task that will delete the expired coupons. The relevant code from the rakefile looks like this:

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

但是失败并显示以下错误消息:

That however fails with the following error message:

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

我只是不知道为什么.需要什么参数?

I'm just not sure why. What arguments would be needed?

作为一项实验,我发现这很有效:

As an experiment, I found that this worked 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

这返回了正确数量的记录,所以我假设我成功地收集了正确的对象.

That returned the right number of records, so I assume I'm successfully gathering up the right objects.

FWIW,我也试过这个,但没有运气:

FWIW, I tried this too, and 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 kind of out of ideas. What am I doing wrong here?

非常感谢您的帮助.如果不是 Stack Overflow,我很确定我不会找到工作!

Thanks so much for your help. I'm pretty sure I wouldn't have a job if it weren't for Stack Overflow!

推荐答案

离你很近了.您只需要使用 #destroy_all 方法而不是 #destroy.后者需要一个 id 参数.

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

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

这篇关于在 rake 中销毁 Rails 3 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆