Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
838 views
in Technique[技术] by (71.8m points)

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...