如何在accomplished_challenge
上触发方法days_left_challenged == 0
?
before_save :days_left_challenged_sets_deadline
# makes ongoing_challenge become past (before_save) THIS WORKS
def days_left_challenged_sets_deadline
if self.date_started != nil
if days_left_challenged <= 0
self.accomplished = true
self.deadline = self.date_started
end
end
end
# makes ongoing_challenge become past (whenever gem) THIS DOESN'T
def self.accomplished_challenge
self.all.each do |challenge|
if challenge.days_left_challenged <= 0
challenge.accomplished = true
challenge.deadline = self.date_started
end
end
end
# Counts down how many days left in days_challenged using committed
def days_left_challenged
self.days_challenged - ((date_started.to_date)..Date.yesterday).count do |date|
committed_wdays.include? date.wday
end + self.missed_days
end
id: 1,
action: "Run",
committed: ["sun", "mon", "tue", "wed", "thu", "fri", "sat", ""],
date_started: Sat, 06 Feb 2016 00:00:00 EST -05:00,
deadline: nil,
accomplished: nil,
days_challenged: 10,
missed_days: 0,
我无法通过回调或验证来触发它我不会认为,因为days_left_challenged
可以在挑战生命中的任何时候转向0
。
答案 0 :(得分:1)
我建议您使用像Whenever之类的宝石来设置每天运行的cron作业,然后检查所有挑战。它会是这样的:
every 1.day, :at => '0:01 am' do
runner "Challenge.accomplished_challenge"
end
您的accomplished_challenge
必须是一个检查所有(或您使用过滤器选择的那个)的类方法挑战:
def self.accomplished_challenge
self.all.each do |challenge|
if challenge.days_left_challenged == 0
challenge.update_attributes(deadline: self.date_started, accomplished: true)
end
end
end
----编辑Heroku ----
在/lib/tasks/scheduler.rake
上创建任务:
# /lib/tasks/scheduler.rake
desc "This task is called by the Heroku scheduler add-on"
task :check_accomplished_challenges => :environment do
puts "Checking accomplished challenges..."
Challenge.accomplished_challenge
puts "done."
end
转到您的heroku app资源页面并添加&#39; Heroku Scheduler&#39;。打开调度程序并添加任务:
rake check_accomplished_challenges
将其设置为每天运行。 更多详情:https://devcenter.heroku.com/articles/scheduler