sql - Use includes() instead of joins() with Rails -


i have 2 models invoice , payevents. relationship between them invoice has_many payevents.

i'm using following query bills have been paid.:

invoice.joins(:payevents).group("invoice.id").having("sum(payevents.amount) >= invoice.amount") 

this query works fine. however, not optimal since result doesn't include payevents. tried use includes instead of joins doesn't work.

invoice.includes(:payevents).group("invoice.id").having("sum(payevents.amount) >= invoice.amount") 

the error is

activerecord::statementinvalid: pg::groupingerror: error:  column "payevents.id" must appear in group clause or used in aggregate function 

any ideas wrong here?

i use postgresql , rails 4.1

if correctly understand - should use subquery. this:

subquery = invoice.joins(:payevents)                   .group("invoice.id")                   .having("sum(payevents.amount) >= invoice.amount")                   .select("invoice.id id, sum(payevents.amount) amount").to_sql  query = invoice.includes(:payevents).joins("join (#{subquery}) subquery on invoice.id = subquery.id") 

so, you'll have invoice, aggregated amount, filtered result inner join of subquery , payevents fields.


Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -