我在编写要在ActiveRecord
对象的集合上使用的类方法时遇到问题。在过去的几个小时里,我遇到过两次这样的问题,它看起来像一个简单的问题,所以我知道我错过了一些东西,但我一直无法在其他地方找到答案。用于收集对象的Rails模型类方法
例子:
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: undefined method 'map' for #<Class:...
据我所知,这是因为map
不能直接在Order
调用,但需要一个Enumerable
对象,而不是。如果我拨打Order.year.map(&:first_for_customer?).count(true)
,我会得到理想的结果。
什么是正确的方式来编写方法使用的对象集合,但不是直接在类上?
完美!这个诀窍会让事情变得更容易。我从来没有意识到我可以在一个关系上调用“全部”,而不仅仅是在课堂上。 – elements
你,先生,是天赐之物。我提交了https://github.com/rails/rails/issues/21943,因为这是一个误导性的文档问题,或者最糟糕的一个错误。 – DreadPirateShawn