佣金任务使客户积分余额到期

时间:2016-06-27 11:06:29

标签: ruby-on-rails activerecord rake

我正在尝试找出如何编写将每天运行的rake任务,并找到剩余天数为0的位置,以便将列数量更新为零。

我在我的模型中定义了以下方法,但它们看起来并不完全正常,因为我在视图中收到以下错误

undefined method `-@' for Mon, 27 Jun 2016:Date

def remaining_days
    expired? ? 0 : (self.expire_at - Date.today).to_i
  end

  def expired?
    (self.expire_at - Date.today).to_i <= 0
  end
def expire_credits
    if expired?
      self.update(:expire_at => Date.today + 6.months, :amount => 0)
    end
  end

使用rake任务我从未写过这些并且我认为我可以调用StoreCredit的方法,如果满足某些条件会使点数到期,但我不确定这一切是如何工作的

task :expire_credits => :environment do
  puts 'Expiring unused credits...'
  StoreCredit.expire_credits
  puts "done."
end

2 个答案:

答案 0 :(得分:1)

# model/store_credit.rb
# get all store_credits that are expired on given date, default to today
scope :expire_on, -> (date = Date.current) { where("expire_at <= ?", date.beginning_of_day) }

class << self
  def expire_credits!(date = Date.current)
    # find all the expired credits on particular date, and update all together 
    self.expire_on(date).update_all(amount: 0)
  end
end

由于这是一项佣金任务,我认为一起更新所有过期的任务会更有效

#rake file
result = StoreCredit.expire_credits!
puts "#{result} records updated"
  

检索记录计数更新

class << self
  def expire_credits!(date = Date.current)
    # find all the expired credits on particular date, and update all together 
    records = self.expire_on(date)
    records.update_all(amount: 0)
    records.length
  end
end

答案 1 :(得分:0)

您调用类方法但定义实例方法。您需要定义类方法:

def self.expire_credits