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

发布于 2024-09-14 04:21:06 字数 578 浏览 6 评论 0原文

不确定我的 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

因此,我试图找到每张发票的周转时间总和,然后将其除以发票总数。

Ruby 抱怨没有为 Class 定义 map 方法。我期望 self 是一个 Array

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

Not sure on my Ruby syntax here.

I want to define a method that I can call like this: client.invoices.average_turnaround. So my average_turnaround method needs to work with a collection of ActiveRecord objects.

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. I was expecting self to be an Array.

How do I write a method that works on a collection of Invoices and uses the map function? Where am I going wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

荒路情人 2024-09-21 04:21:06

如果您想在类方法中使用映射而不是通过关联扩展。例如,如果直接调用 Invoice.average_turnaroundInvoice.where(x: y).average_turnaround 很有用。将 all. 放在 map 前面。

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

使用任何集合使用average_turnaround

If you want to use map within the class method as opposed to through an association extension. For example if it would be useful to call Invoice.average_turnaround directly or Invoice.where(x: y).average_turnaround. Place all. in front of map.

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

Use average_turnaround using any collection.

梦与时光遇 2024-09-21 04:21:06

您定义了一个类方法,该方法在类本身上调用。您需要的是关联扩展。该方法应该在您的客户端模型上定义,如下所示:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文