1 Comment

Get Sum of field from associated table in Rails/Mysql

Sometime you have relationship like  campaign has_many causes and need to calculate sum of raise_amount raised from each campaign from the associated table

In mysql this can be done by a simple query

select campaigns.name,SUM(raises.raise_amount) as total_sum FROM campaigns LEFT OUTER JOIN raises ON campaigns.id=raises.campaign_id GROUP BY campaigns.id;

In Rails it can be achieved by this query

Campaign.joins(“LEFT OUTER JOIN raises on campaigns.id = raises.campaign_id”).group(“campaigns.id”).order(“SUM(raises.raise_amount) DESC”)

it takes a couple of hours to figure it out. might it save others time.

 

Advertisements

One comment on “Get Sum of field from associated table in Rails/Mysql

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: