Home ActiveRecord where condtion on selected query result
Reply: 1

ActiveRecord where condtion on selected query result

Ferdinand Rosario
1#
Ferdinand Rosario Published in 2018-01-09 06:09:50Z
Borrower.joins("INNER JOIN receivables ON receivables.borrower_id = borrowers.id")
.where("borrowers.type='moulde_b'")
.select(" borrowers.id as id,sum(receivables.amount) as invoice_amount");

from the above result set I'm trying to do where condition after the select statement.

I'm trying something like the below,

Borrower.joins("INNER JOIN receivables ON receivables.borrower_id = borrowers.id")
    .where("borrowers.type='moulde_b'")
    .select(" borrowers.id as id,sum(receivables.amount) as invoice_amount").where("receivables.amount = 12323.23");

is this really possible to do after select where condtion on the SUM column.

mudasobwa
2#
mudasobwa Reply to 2018-01-09 06:25:29Z

Use ActiveRecord::QueryMethods#having instead of where:

Borrower.
  joins("INNER JOIN receivables ON receivables.borrower_id = borrowers.id").
  where("borrowers.type = 'moulde_b'").
  select("borrowers.id as id, sum(receivables.amount) as invoice_amount").
  group("borrowers.id"). # mandatory for having
  having("invoice_amount = 12323.33")

The order of chaining these methods does not really matter, since AR would rearrange it while building the real SQL query anyway.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.320188 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO