问题描述
我有一个模型,从获取特定城市的所有游戏。当我拿到这些游戏我要过滤他们,我想使用拒绝
的方法,但我遇到了一个错误,我想明白了。
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 ?
推荐答案
所不同的是,你在呼唤拒绝
的对象。在视图中, @games
的活动记录对象的数组,因此调用 @ games.reject
使用阵列#拒绝
。在你的模型,你调用拒绝
在自
中的一类方法,这意味着它试图调用 Matches.reject
,它不存在。您需要首先获取的记录,像这样的:
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
这篇关于ActiveRecord的使用拒绝方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!