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 ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…