如何使用“地图”? ActiveRecord 类方法中的方法?
不确定我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想在类方法中使用映射而不是通过关联扩展。例如,如果直接调用
Invoice.average_turnaround
或Invoice.where(x: y).average_turnaround
很有用。将all.
放在map
前面。使用任何集合使用
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 orInvoice.where(x: y).average_turnaround
. Placeall.
in front ofmap
.Use
average_turnaround
using any collection.您定义了一个类方法,该方法在类本身上调用。您需要的是关联扩展。该方法应该在您的客户端模型上定义,如下所示:
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: