Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord and using reject method

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 ?

like image 568
alenm Avatar asked Feb 25 '23 21:02

alenm


1 Answers

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
like image 65
Jimmy Avatar answered Mar 08 '23 06:03

Jimmy