【问题标题】:Rails 4: Get sum of all subchildrenRails 4:获取所有子项的总和
【发布时间】:2014-01-01 20:30:55
【问题描述】:

我有三个模型 Customer、Invoice、InvoiceItems。其中 Customer has_many Invoices,Invoices has_many InvoiceItems。

InvoiceItems 的属性之一是“金额”。我想为每个客户打印所有发票的总金额。在 Rails 4 中最有效和最优雅的方式是什么?

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-4


    【解决方案1】:

    如果你想完全在 SQL 中完成,你可以使用:

    Customer.joins(invoices: :invoice_items).select('customers.id, sum(amount) as total')
      .group('customers.id').each {|ar| puts ar.id, ar.total}
    

    如果您愿意,当然可以更改selectgroup 以使用customers.id 之外的其他内容。

    混合方法是:

    Customer.each do |customer|
      total = customer.invoices.inject(0) do |total, invoice|
        total+invoice.invoice_items.sum('amount')
      puts customer.id, total
      end
    end
    

    【讨论】:

    • 谢谢,这很好用。但是,每个客户有大约 100 张发票,而每张发票大约有 20 件。因此,运行此查询需要相当长的时间。是否可以为每张发票(发票项目可能会更改)或至少为每个客户添加单独的缓存?
    • 抱歉,我对 Rails 缓存一无所知。您可能想提出一个专门针对该问题的新问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 2020-12-09
    • 2019-05-04
    • 1970-01-01
    相关资源
    最近更新 更多