【问题标题】:Column Calculations Rails 3列计算 Rails 3
【发布时间】:2011-07-06 22:17:16
【问题描述】:

我的应用有发票和 invoice_items。每张发票都有许多 invoice_items。

在我的 invoice_items 模型中,我有一个计算来计算总数:

def total
   @total ||= quantity.to_d * price
end

效果很好。我想做的是计算总数的总和,但我被卡住了。

在控制台中,我试过这个:

invoice = Invoice.first
invoice.invoice_items.sum(:total)

但我收到一条错误消息:总计不存在。我猜它不会。

我的问题是如何进行这个计算?

-- 更新--

我根据@paukul 的回答尝试了以下方法:

invoice.invoice_items.sum(&:total)

这给出了错误:

ArgumentError: wrong number of arguments (1 for 2)

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您在整个 invoice_items 数组(显然不知道 .total 方法)上调用 .sum 而不是每个单独的发票项目。 为了使其工作,您需要使用 sum 的块版本,它将数组中的每个项目都生成到块中并将它们的结果相加。

    使用 proc 语法糖的符号,你就快到了。 试试invoice.invoice_items.all.sum(&:total) 相当于invoice.invoice_items.inject(0) { |sum, item| sum + item.total }

    RDoc for Enumerable#sum

    【讨论】:

    • 感谢您的帮助。尝试 top 方法时,出现错误。更新了我的第一个问题。 Jx
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 2023-03-14
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    相关资源
    最近更新 更多