ActiveRecord 和使用拒绝方法

发布于 2024-10-20 05:51:01 字数 695 浏览 2 评论 0原文

我有一个模型可以获取特定城市的所有游戏。当我得到这些游戏时,我想过滤它们,并且想使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟酒忠诚 2024-10-27 05:51:01

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

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文