ActiveRecord查询以总结连接

时间:2016-01-06 10:02:03

标签: sql ruby-on-rails postgresql activerecord

我希望获得特定预算(相同标题)中的收据项目的总和,并且从当前查询中得到许多记录以及来自收据项目的明显错误的金额总和。

我目前的尝试在ActiveRecord(AR)中看起来像那样:

ReceiptItem.includes(donation: [:budgets]).joins(:donation, :receipt).where(budgets: {title: "Some title 2015"}).sum(:amount)

我的SQL尝试看起来像那样(也是错误的):

-- want to test just the outcome its not actually not summing up the amounts
SELECT "receipt_items"."amount"
FROM
  "receipt_items" INNER JOIN "donations" ON "donations"."id" = "receipt_items"."donation_id"
    RIGHT JOIN "receipts" ON "receipts"."receipt_id" = "receipt_items"."receipt_id"
    LEFT OUTER JOIN "budgets" ON "budgets"."donation_id" = "donations"."id"
WHERE "budgets"."title" = 'Some title 2015';

为什么我会得到双重记录,虽然我已经加入了表并设置了条件?

这是解决问题的ER模式。 ER model

这是AR Assoziations:

class Budget < ActiveRecord::Base
  belongs_to :donation
class Donation < ActiveRecord::Base
    has_many :receipt_items
    has_many :budgets
class ReceiptItem < ActiveRecord::Base
  belongs_to :donation

1 个答案:

答案 0 :(得分:1)

由于预算可以通过不同的捐款多次链接到收据项目,因此会多次出现在大型联接表中,因此会被计算好几次。

让我们试着一步一步地思考这个问题。如果你想这样做而不用担心急切加载,你会这样做:

Budget.where(title: "some title").all.collect(&:donation).collect(&:receipt_items).flatten.uniq.collect(&:amount).sum

是吗?

如果是这样,您可以定制热切加载以适应此方法调用链:

Budget.where(title: "some title", include: {:donation => [:receipt_items]}).all.collect(&:donation).collect(&:receipt_items).uniq.collect(&:amount).sum

试试吗?