title: rails 3 group by and sum
body: <p>I have the following model:</p>
  
  <pre><code>activity_types: id, name
  
  activities: id, id_activity_type, occurrences, date (other fields)
  </code></pre>
  
  <p>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.</p>
  
  <p>I got the following solution <a href="https://stackoverflow.com/questions/499767/counting-and-grouping-at-the-same-time">based on this post</a> which seems ok:</p>
  
  <pre><code>Activity.all(:joins =&gt; :activity_types,
               :select =&gt; "activity_types.id, activity_types.name, SUM(activities.occurrences) as occurrences",
               :group =&gt; "activity_types.id, activity_types.name",
               :order =&gt; "activity_types.id")
  </code></pre>
  
  <p>but this seems a lot of code for the rails standards and <a href="http://apidock.com/rails/ActiveRecord/Base/find/class" rel="nofollow noreferrer">rails API says it's deprecated</a>.</p>
  
  <p>I found the following solution which is a lot simple:</p>
  
  <pre><code>Activity.sum(:occurrences).group(:activity_type_id)
  </code></pre>
  
  <p>Which returns an hash with <strong>activity_type_id</strong> => occurrences. </p>
  
  <p>What shall I do to get the following hash: <strong>activity_type.name</strong> => occurrences ? </p>