Bharat
Bharat

Reputation: 2459

Group Query in Rails involving associations

I have two tables (and associated models) in my Rails database with a one-to-many relationship.

billable_totals
---------------
id
project_id
adjusted_amount

projects
---------
id
project_type

The associated models are BillableTotal and Project with the following relationships:

BillableTotal belongs_to Project
Project has_many BillableTotals

I want to do a group query which outputs the project_type from projects table and the sum of adjusted_amount from billable_totals grouped by project_type. I am running into all sorts of problems. Both activerecord and Postgres keep complaining. Please advise on how to structure this query.

Upvotes: 0

Views: 254

Answers (1)

Albin
Albin

Reputation: 3012

I think this should work:

Project.joins(:billable_totals).group(:project_type).sum('billable_totals.adjusted_amount')

I could at least run a query on that format in my own project and get reasonable results.

Upvotes: 1

Related Questions