我有一个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任务,这是我到目前为止所得到的错误未定义方法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
答案 0 :(得分:1)
如果预测:has_many结果,则结果现在是一个集合,您将不得不这样对待它。你不能说,
prediction.result.home_score
您必须使用数组索引引用结果,例如
prediction.results[0].home_score
或迭代结果集合,如:
prediction.results.each do |result|
result.home_score # do something with the score
end
我意识到这并不能完全回答“如何重构”问题,但如果预测:has_many结果,你就不能简单地引用prediction.result了。
希望有所帮助。