I have a model that fetches all the games from a particular city. When I get those games I want to filter them and I would like to use the reject method, but I’m running into an error I’m trying to understand.
# STEP 1 - Model
class Matches < ActiveRecord::Base
def self.total_losses(cities)
reject{ |a| cities.include?(a.winner) }.count
end
end
# STEP 2 - Controller
@games = Matches.find_matches_by("Toronto")
# GOOD! - Returns ActiveRecord::Relation
# STEP 3 - View
cities = ["Toronto", "NYC"]
@games.total_losses(cities)
# FAIL - undefined method reject for #<Class:0x00000101ee6360>
# STEP 3 - View
cities = ["Toronto", "NYC"]
@games.reject{ |a| cities.include?(a.winner) }.count
# PASSES - it returns a number.
Why does reject fail in my model but not in my view ?
The difference is the object you are calling
rejecton. In the view,@gamesis an array of Active Record objects, so calling@games.rejectusesArray#reject. In your model, you’re callingrejectonselfin a class method, meaning it’s attempting to callMatches.reject, which doesn’t exist. You need to fetch records first, like this: