HABTM Associations in Rails: collecting and counting the categories of children in a model


I have a has_and_belongs_to_many relationship setup. It looks like this:

  • books have_and_belong_to_many categories
  • categories have_and_belongs_to_many books
  • a store has_many books
  • a book belongs_to a store

I'm trying to show how many books in each store belong to each category. So my view would show Store X has 200 books and 80 of them are mystery, 60 are non fiction, etc.

I have been trying out a bunch of different ways of doing this, but no success so far. I think I'm starting in the wrong place. Any direction would be much appreciated.


This is Rails 4 and psql by the way.

Provided that you have a books_categories join table you can add a has_many :categories, through: :books association to which links stores and categories through books.

class Store < ActiveRecord::Base
  has_many :books
  has_many :categories, through: :books

That's the easy part. Now lets get each category and the books count (revised):

def books_per_category
  categories.select('categories.id, categories.name, count(books.id) as count').group('categories.id, categories.name').map do |c|
      name: c.name,
      count: c.count

Courtesy of @jakub-kosiƄski