简体   繁体   English

如何在ActiveRecord类方法中使用“地图”方法?

[英]How do I use the 'map' method in an ActiveRecord class method?

Not sure on my Ruby syntax here. 在这里不确定我的Ruby语法。

I want to define a method that I can call like this: client.invoices.average_turnaround . 我想定义一个可以像这样调用的方法: client.invoices.average_turnaround So my average_turnaround method needs to work with a collection of ActiveRecord objects. 因此,我的average_turnaround方法需要使用ActiveRecord对象的集合。

Here's my code thus far: 到目前为止,这是我的代码:

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

So I'm trying to find the sum of the turnaround times for each invoice, then divide it by the total number of invoices. 因此,我试图找到每个发票的周转时间总和,然后将其除以发票总数。

Ruby is complaining that there is no map method defined for Class . Ruby抱怨没有为Class定义map方法。 I was expecting self to be an Array . 我期望self是一个Array

How do I write a method that works on a collection of Invoices and uses the map function? 如何编写适用于Invoices集合并使用map函数的方法? Where am I going wrong? 我要去哪里错了?

If you want to use map within the class method as opposed to through an association extension. 如果要在类方法中使用map而不是通过关联扩展名。 For example if it would be useful to call Invoice.average_turnaround directly or Invoice.where(x: y).average_turnaround . 例如,如果直接调用Invoice.average_turnaroundInvoice.where(x: y).average_turnaround是有用的。 Place all. all.放置all. in front of map . map前面。

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

Use average_turnaround using any collection. 使用任何集合使用average_turnaround

You defined a class method, which is called on the class itself. 您定义了一个类方法,该方法在类本身上被调用。 What you need is an association extension . 您需要的是关联扩展 The method should be defined on your client model like this: 该方法应在您的客户端模型上定义,如下所示:

class Client < ActiveRecord::Base
  has_many :invoices do
    def average_turnaround
      return map(&:turnaround).inject(:+) / count
    end    
  end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM