This question is an offshoot from HABTM associations in Rails : collecting and counting the categories of a model's children.
class Cate
You can use chain select
and group
to aggregate the count of books for each category. Your books_per_category
method may look like this:
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
}
end
end
This will produce the following SQL query:
SELECT categories.id, categories.name, count(books.id) as count
FROM "categories"
INNER JOIN "books_categories" ON "categories"."id" = "books_categories"."category_id"
INNER JOIN "books" ON "books_categories"."book_id" = "books"."id"
WHERE "books"."store_id" = 1
GROUP BY categories.id, categories.name