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 reject
on. In the view, @games
is an array of Active Record objects, so calling @games.reject
uses Array#reject
. In your model, you're calling reject
on self
in a class method, meaning it's attempting to call Matches.reject
, which doesn't exist. You need to fetch records first, like this:
def self.total_losses(cities)
all.reject { |a| cities.include(a.winner) }.count
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With