Destroying a Rails 3 object in rake?

前端 未结 2 1192
臣服心动
臣服心动 2021-01-26 05:34

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

相关标签:
2条回答
  • 2021-01-26 05:45

    First off, to help debug things from rake, invoke it with the --trace option. Your issue here isn't rake specific though.

    The Offer.where('expires_on < ?', today) is going to return a collection, and not a single instance of Offer and there isn't a destroy method available for the collection.

    You can iterate over each expired offer and call destroy. Something like this:

    @offers = Offer.where('expires_on < ?', today)
    @offers.each { |offer| offer.destroy }
    
    0 讨论(0)
  • 2021-01-26 05:55

    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
    
    0 讨论(0)
提交回复
热议问题