下面的SQL查询在Postgres中产生一个精确的计算:
select sum(invoice_items.unit_price * discounts.percentage/100) as discount from invoice_items join items on items.id = invoice_items.item_id join merchants on merchants.id = items.merchant_id join discounts on discounts.merchant_id = merchants.id where invoice_items.quantity >= discounts.threshold and invoice_items.invoice_id = 513;
对应的ActiveRecord正在生成成功的SQL语句:
invoice_items.select('sum(invoice_items.unit_price * discounts.percentage/100)')
.joins(:discounts)
.where('invoice_items.quantity >= discounts.threshold')
AR返回一个ActiveRecord_AssociationRelation
…但是我不能让AR输出实际的SUM。
问题:如何更新AR表达式以返回SUM函数的实际值?
我试过了:
- 将SUM函数混叠,然后在生成的
AssocationRelation
上调用它 - 通过
AssociationRelation
迭代调用别名(方法不存在) - 删除SUM函数,添加别名,然后迭代结果,但我需要返回和....
可能问这个问题太早了....我已经解决了这个问题。
我更新ActiveRecord查询如下:
invoice_items.select('invoice_items.unit_price * discounts.percentage/100 as calculated_discount')
.joins(:discounts)
.where('invoice_items.quantity >= discounts.threshold')
然后在视图中调用
@invoice.discount.sum(&:calculated_discount)