我有一个 rake 任务,它在比较预测和结果时分配一个分数,目前关系是 has_one,如预测 has_one :result..
我想将其更改为预测 has_many :results。我的任务看起来像这样
namespace :grab do
task :scores => :environment do
Prediction.all.each do |prediction|
score = points_total prediction, prediction.result
allocate_points prediction, score
end
end
end
def points_total(prediction, result)
wrong_predictions = [prediction.home_score - result.home_score, prediction.away_score - result.away_score]
wrong_predictions = wrong_predictions.reject { |i| i == 0 }.size # returns 0, 1 or 2
case wrong_predictions
when 0 then 3
when 1 then 1
else 0
end
end
def allocate_points(prediction, score)
prediction.update_attributes!(score: score)
end
在运行任务的那一刻,我得到了错误
undefined method result for Prediction Class
因此,通过 has_many 关系,我可以通过以下方式访问结果属性
prediction.result.home_score
还是我在某个地方感到困惑。我不知道如何重构我的 rake 任务以适应新的关系
任何建议表示赞赏
编辑
即使在收到来自@andrunix 的以下建议后,似乎也无法弄清楚如何应用于 rake 任务,这就是我到目前为止所拥有的,但得到错误 undefined method to_i for array
namespace :grab do
task :scores => :environment do
Prediction.all.each do |prediction|
score = points_total prediction
allocate_points prediction, score
end
end
end
def points_total prediction
prediction.results.each do |result|
result_h = result.home_score
result_a = result.away_score
wrong_predictions = [prediction.home_score - result_h, prediction.away_score - result_a]
wrong_predictions = wrong_predictions.reject { |i| i == 0 }.size # returns 0, 1 or 2
case wrong_predictions
when 0 then 3
when 1 then 1
else 0
end
end
end
def allocate_points prediction, score
prediction.update_attributes!(score: score)
end