如何在ActiveRecord类方法中使用'map'方法?

nfm*_*nfm 1 ruby collections activerecord ruby-on-rails map

我不确定我的Ruby语法.

我想定义一个我可以这样调用的方法:client.invoices.average_turnaround.所以我的average_turnaround方法需要使用一组ActiveRecord对象.

到目前为止,这是我的代码:

class Invoice < ActiveRecord::Base
  ...
  def self.average_turnaround
    return self.map(&:turnaround).inject(:+) / self.count
  end
end
Run Code Online (Sandbox Code Playgroud)

所以我试图找出每张发票的周转时间总和,然后除以发票总数.

Ruby抱怨没有map定义方法Class.我原以为self是一个Array.

如何编写一个适用于该集合Invoices并使用该map函数的方法?我哪里错了?

keq*_*quc 6

如果要在类方法中使用map而不是通过关联扩展.例如,如果Invoice.average_turnaround直接或直接呼叫是有用的Invoice.where(x: y).average_turnaround.将all.前面map.

class Invoice < ActiveRecord::Base
  ...
  def self.average_turnaround
    all.map(&:turnaround).inject(:+) / all.count
  end
end
Run Code Online (Sandbox Code Playgroud)

使用average_turnaround任何集合.