title: ActiveRecord group by on a join
body: <p>Really been struggling trying to get a group by to work when I have to join to another table.  I can get the group by to work when I don't join, but when I want to group by a column on the other table I start having problems.</p>
  
  <pre><code>Tables:
  Book
  id, category_id
  
  Category
  id, name
  
  ActiveRecord schema:
  
  class Category &lt; ActiveRecord::Base
    has_many :books
  end
  
  class Book &lt; ActiveRecord::Base
    belongs_to :category
  end
  </code></pre>
  
  <p>I am trying to get a group by on a count of categories.  I.E. I want to know how many books are in each category.</p>
  
  <p>I have tried numerous things, here is the latest,</p>
  
  <pre><code>books = Book.joins(:category).where(:select =&gt; 'count(books.id), Category.name', :group =&gt; 'Category.name')
  </code></pre>
  
  <p>I am looking to get something back like</p>
  
  <pre><code>[{:name =&gt; fiction, :count =&gt; 12}, {:name =&gt; non-fiction, :count =&gt; 4}]
  </code></pre>
  
  <p>Any ideas?</p>
  
  <p>Thanks in advance!</p>