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

2024-02-28

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

Example:

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, I get 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 子句,您仍然可以从该 where 子句中获得结果,这样,如果您直接调用此方法,您将获得所需的结果Order.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

用于收集对象的 Rails 模型类方法 的相关文章

随机推荐