ActiveRecord的使用拒绝方法 [英] ActiveRecord and using reject method

查看:327
本文介绍了ActiveRecord的使用拒绝方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,从获取特定城市的所有游戏。当我拿到这些游戏我要过滤他们,我想使用拒绝的方法,但我遇到了一个错误,我想明白了。

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的使用拒绝方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆