Search code examples
ruby-on-railsrails-activerecord

Rails ActiveModel get sum of calculated column


How can I perform calculations on calculated columns in ActiveRecord?

I have a model Position

class Position < ApplicationRecord
  belongs_to :invoice
  belongs_to :vat_type
end

The following works and gives me each row's calculated value of posi_price

Position.select('invoice_id, amount, price,
    amount*price AS posi_price, vat_type_id')
    .where('vat_type_id = ? AND invoice_id = ?', vat_type.id,@invoice.id)
    .each do |p|
        puts p.posi_price
    end

Now I would like to omit the .each loop and calculate just the sum of posi_price as selected in the above query. However,

Position.select('invoice_id, amount, price,
    amount*price AS posi_price, vat_type_id')
    .where('vat_type_id = ? AND invoice_id = ?', vat_type.id,@invoice.id).sum(:posi_price)

gives no such column: posi_price. I can also observe that only a lazy query is executed:

SELECT SUM(posi_price) FROM "positions" WHERE (vat_type_id = 1 AND invoice_id = 6)

I have tried numerous combinations of .all .each .pluck etc. but was not able to get to this sum.


Solution

  • .sum on a ActiveRecord::Relation uses .calculate under the hood.

    The documentation of it has an example of what you need. It accepts not just symbols for column names, but also literal SQL strings.

    Position
      .where('vat_type_id = ? AND invoice_id = ?', vat_type.id, @invoice.id)
      .sum('amount*price')