用于集合对象的Rails模型类方法

我在编写用于ActiveRecord对象集合的类方法时遇到了麻烦。 我在最近几个小时内遇到过这个问题两次,这似乎是一个简单的问题,所以我知道我错过了一些东西,但我无法在其他地方找到答案。

例:

 class Order  { 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: undefined method 'map' for #<Class:...

据我所知,这是因为map不能直接在Order上调用,而是需要一个Enumerable对象。 如果我调用Order.year.map(&:first_for_customer?).count(true) ,我会得到所需的结果。

编写用于ActiveRecord对象集合的方法的正确方法是什么,而不是直接在类上?

在您的情况下,您可以在这种情况下使用技巧。

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

如果你在where子句上连接这个方法,你仍然可以得到结果,这样就可以做到这一点,这样你就可以直接在Order上调用这个方法。

ActiveRecord集合通常使用范围进行操作,其优点是能够链接它们并让数据库完成繁重的工作。 如果你必须在Ruby中管理它,你可以从all开始。

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

你想用你的代码做什么呢?