ActiveRecord 和使用拒绝方法
我有一个模型可以获取特定城市的所有游戏。当我得到这些游戏时,我想过滤它们,并且想使用 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.
为什么 reject
在我的模型中失败,但在我的视图中却没有?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
区别在于您调用
reject
的对象。在视图中,@games
是 Active Record 对象的数组,因此调用@games.reject
使用Array#reject
。在您的模型中,您在类方法中对self
调用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
usesArray#reject
. In your model, you're callingreject
onself
in a class method, meaning it's attempting to callMatches.reject
, which doesn't exist. You need to fetch records first, like this: