Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading