The problem is because of being a rake task but because of the methods themselves.
Both your Prediction and Result models have a home_score
method, but they are instance methods and not class methods as you are trying to use them in your points_total
and allocate_points
methods.
The difference between a class and an instance method is the object in which the method is called:
- Class method: is called on the Model itself, as in
User.new
. Thenew
method is called on theUser
model to generate a new instance of the Model. - Instance method: is callen on a specific instance of a model, as in
my_user.name = "Terminator"
. Thename
method is called on the specificmy_user
User to change its (and just its) name.
Looking at your code, your methods home_score are thought to be applied on specific instances of predictions and results, as they are instance methods. This is the error that the console is throwing, the methods are not available for the Class (the Model).
Assuming your rake task is trying to update the total points of each Prediction in your database, the code would be:
lib/tasks/grab.rake
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
However, that is a kind of 'pseudo-code' because some relation between Prediction and Result models should exist in order to use them as in points_total method. My code is assuming a has_one association, which sould be also reflected in the models; but as I do not know exactly the whole picture for your app I did not want to change this, just focusing on the rake methods.
Hope that helps,