我有一个用户可以互相下注的应用程序,当结果加载到应用程序中时,我使用 Rake 任务来结算赌注。我在 Heroku 上运行,所以我每半小时使用他们的调度服务来执行这个 Rake 任务。
这工作正常,但我更想在数据库中保存/更新结果时运行 Rake 作业。
如何转换 Rake 任务,以便可以从我的模型中运行它,如下所示。如果我可以从控制器运行它也可能会很好,因为我可能有几种需要结算过程的情况。
class Spotprice < ActiveRecord::Base
belongs_to :spotarea
belongs_to :product
after_save :settlement
end
我的 Rake 任务现在看起来像这样:
task :settlement => :environment do
puts "Settlement in progress..."
puts "-------------------------"
puts " "
puts " "
puts "BETS:"
puts "-------------------------"
# Bet settlement
@bets = Bet.where(:settled => false)
@bets.find_each do |bet|
if not bet.choice.spotprice.nil?
case
when bet.choice.spotprice.value > bet.choice.value && bet.buy == true
profitloss = 10
puts "#{bet.id}: Win (1)"
when bet.choice.spotprice.value < bet.choice.value && bet.buy == false
profitloss = 10
puts "#{bet.id}: Win (2)"
when bet.choice.spotprice.value > bet.choice.value && bet.buy == false
profitloss = -10
puts "#{bet.id}: Loose (3)"
when bet.choice.spotprice.value < bet.choice.value && bet.buy == true
profitloss = -10
puts "#{bet.id}: Loose (4)"
when bet.choice.spotprice.value == bet.choice.value
profitloss = -10
puts "#{bet.id}: Loose (5)"
end
if profitloss
bet.settled = true
bet.profitloss = profitloss
bet.save
end
end
if bet.choice.settled == true
bet.choice.settled = false
bet.choice.save
end
end
# Pusher update
Pusher["actives"].trigger("updated", {:message => "Settlement completed"}.to_json)
end