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 ?
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With