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

时间:2015-07-01 07:28:28

标签: ruby-on-rails ruby activerecord

我在编写用于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

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

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

ActiveRecord个对象上编写方法的正确方法是什么,但不能直接在类上使用?

2 个答案:

答案 0 :(得分:11)

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

/rooms

这样做可以解决这个问题,没有任何其他问题,如果你在where子句上连接这个方法,你仍然可以得到结果,这样你就可以直接在def self.first_order_count all.map(&:first_for_customer?).count(true) end 调用这个方法得到你需要的东西

答案 1 :(得分:4)

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

all

你想用代码实现什么目标?