title: Get all records grouped by field from association and sorted by count in group
body: <p>I have 3 models: <code>Post</code>, <code>Comment</code>, <code>User</code></p>
  
  <p><code>Post</code> has many <code>Comments</code></p>
  
  <p><code>Comment</code> belongs to <code>User</code></p>
  
  <p><code>User</code> has field <code>country_code</code></p>
  
  <p>I want to get all post comments grouped by country code AND sorted by amount of comments per country.</p>
  
  <p>This query:</p>
  
  <pre><code>post.comments.joins(:user).group("users.country_code").order('count_all desc').count
  </code></pre>
  
  <p>returns such kind of result:</p>
  
  <pre><code>{"DE"=&gt;67,
  "US"=&gt;8,
  "RS"=&gt;8,
  "IN"=&gt;8,
  "ES"=&gt;7,
  "BR"=&gt;6,
  ...
  "UA"=&gt;0
  </code></pre>
  
  <p>}</p>
  
  <p>What I need is a similar result where country codes are keys but values are arrays of comments. I don't know how to achieve this.</p>