Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3 group by and sum

I have the following model:

activity_types: id, name

activities: id, id_activity_type, occurrences, date (other fields)

The activities table store how many times an activity occurs by day. But now I want to show to the user how many activities from each type occurred by month.

I got the following solution based on this post which seems ok:

Activity.all(:joins => :activity_types,
             :select => "activity_types.id, activity_types.name, SUM(activities.occurrences) as occurrences",
             :group => "activity_types.id, activity_types.name",
             :order => "activity_types.id")

but this seems a lot of code for the rails standards and rails API says it's deprecated.

I found the following solution which is a lot simple:

Activity.sum(:occurrences).group(:activity_type_id)

Which returns an hash with activity_type_id => occurrences.

What shall I do to get the following hash: activity_type.name => occurrences ?

like image 707
dcarneiro Avatar asked Jan 30 '12 18:01

dcarneiro


1 Answers

If the original query worked, then just try rewriting it with Rails 3 syntax:

Activity.joins(:activity_types)
  .select("activity_types.id, activity_types.name, SUM(activities.occurrences) as occurrences")
  .group("activity_types.id, activity_types.name")
  .order("activity_types.id")
like image 183
Marek Příhoda Avatar answered Nov 15 '22 18:11

Marek Příhoda