ActiveRecord的使用拒绝方法

编程入门 行业动态 更新时间:2024-10-28 18:34:25
本文介绍了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的使用拒绝方法

本文发布于:2023-10-13 09:22:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1487562.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   ActiveRecord

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!