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

ele*_*nts 11 ruby activerecord ruby-on-rails

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

例:

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
Run Code Online (Sandbox Code Playgroud)

如果我打电话Order.month.first_order_count,我会 NoMethodError: undefined method 'map' for #<Class:...

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

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

Ner*_*min 11

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

def self.first_order_count
   all.map(&:first_for_customer?).count(true)
end
Run Code Online (Sandbox Code Playgroud)

如果你在where子句上连接这个方法,你仍然可以获得结果,这样就可以解决这个问题,这样你就可以直接调用这个方法得到你需要的东西Order.


fyl*_*ooi 5

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

def self.first_order_count
  all.map(&:first_for_customer?).count(true)
end
Run Code Online (Sandbox Code Playgroud)

你想用你的代码实现什么?