Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby ActiveRecord和使用拒绝方法_Ruby_Ruby On Rails 3_Activerecord_Enumeration - Fatal编程技术网

Ruby ActiveRecord和使用拒绝方法

Ruby ActiveRecord和使用拒绝方法,ruby,ruby-on-rails-3,activerecord,enumeration,Ruby,Ruby On Rails 3,Activerecord,Enumeration,我有一个模型,从一个特定的城市获取所有的游戏。当我得到这些游戏时,我想过滤它们,我想使用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 = Ma

我有一个模型,从一个特定的城市获取所有的游戏。当我得到这些游戏时,我想过滤它们,我想使用
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 #<Class:0x00000101ee6360>

# STEP 3 - View
cities = ["Toronto", "NYC"]
@games.reject{ |a| cities.include?(a.winner) }.count
# PASSES - it returns a number.
#步骤1-模型
类匹配

为什么
reject
在我的模型中失败了,但在我的视图中没有失败?

区别在于您调用的对象是
reject
。在视图中,
@games
是活动记录对象的数组,因此调用
@games.reject
使用
数组#reject
。在您的模型中,您在类方法中调用
self
上的
reject
,这意味着它试图调用不存在的
Matches.reject
。您需要先获取记录,如下所示:

def self.total_losses(cities)
  all.reject { |a| cities.include(a.winner) }.count
end

谢谢你的反馈,我注意到你的博客上有一篇很好的文章解释了
self
的用法。对其他感兴趣的人来说,这是一本好书。还有一个问题——只是好奇,如果你认为这种逻辑存在于模型中是有意义的,还是应该去其他地方?@neuone-是的,它在模型中是有意义的。然而,查找带有条件的记录要比提取所有记录并在事后过滤它们更有效。