Rails的模型类方法的集合对象 [英] Rails model class method for collection of objects

查看:289
本文介绍了Rails的模型类方法的集合对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法写作课的方法来对的ActiveRecord 对象的集合使用。我在过去的几个小时,遇到这个问题两次,这似乎是一个简单的问题,所以我知道我失去了一些东西,但我一直没能找到答案,在其他地方。

I'm having trouble writing class methods to use on collections of ActiveRecord objects. I've run into this issue twice in the last couple of hours, and it seems like a simple problem, so I know I'm missing something, but I haven't been able to find answers elsewhere.

例如:

class Order < ActiveRecord::Base

  belongs_to :customer

  scope :month, -> { where('order_date > ?', DateTime.now.beginning_of_month.utc) }

  def self.first_order_count
    map(&:first_for_customer?).count(true)
  end

  def first_for_customer?
    self == customer.orders.first
    # this self == bit seems awkward, but that's a separate question...
  end

end

如果我称之为 Order.month.first_order_count ,我得到 NoMethodError:未定义的方法图#&LT;班级:...

If I call Order.month.first_order_count, I get NoMethodError: undefined method 'map' for #<Class:...

据我所知,这是因为地图不能直接在订单调用,但需要一个可枚举对象来代替。如果我称之为 Order.year.map(安培;:?first_for_customer)。算(真),我得到了想要的结果。

As far as I know, that's because map can't be called directly on Order, but needs an Enumerable object instead. If I call Order.year.map(&:first_for_customer?).count(true), I get the desired result.

什么是正确的方式写在的ActiveRecord 对象的集合使用方法,而不是通过类直接?

What's the right way to write methods to use on a collection of ActiveRecord objects, but not on the class directly?

推荐答案

在你的情况,你可以在这种情况下,使用一个小技巧。

In your case, you can use a trick in this case.

def self.first_order_count
   all.map(&:first_for_customer?).count(true)
end

会做的伎俩,没有任何其他的问题,这样一来,如果您连接在where子句你仍然得到的结果,其中,这样一来你得到你所需要的,如果你直接调用该方法对订单。

这篇关于Rails的模型类方法的集合对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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