ActiveRecord and using reject method

点点圈 提交于 2020-01-02 10:02:28

问题


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 ?


回答1:


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


来源:https://stackoverflow.com/questions/5207424/activerecord-and-using-reject-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!