ActiveRecord并使用reject方法
我有一个模型可以从特定城市获取所有游戏。 当我得到那些游戏时,我想过滤它们,我想使用reject
方法,但我遇到了一个我想要理解的错误。
# 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 # # STEP 3 - View cities = ["Toronto", "NYC"] @games.reject{ |a| cities.include?(a.winner) }.count # PASSES - it returns a number.
为什么reject
在我的模型中失败但在我看来不是?
区别在于您要reject
的对象。 在视图中, @games
是一个Active Record对象数组,所以调用@games.reject
使用Array#reject
。 在你的模型中,你在类方法中调用self
reject
,这意味着它试图调用不存在的Matches.reject
。 您需要先获取记录,如下所示:
def self.total_losses(cities) all.reject { |a| cities.include(a.winner) }.count end