Reputation: 197
I have a many to many relationship between Items
and Categories
.
I am trying to pull out the number of items belonging to each category in next format: [category.id, <number of items>]
Here is what I have so far:
Category.joins(:items).select('id, count(id) as quantity')
But it doesn't work. Could anyone help me and point to the right direction?
Upvotes: 0
Views: 607
Reputation: 30453
There are multiple problems:
id, count(id) as quantity
is ambiguous, categories.id, count(items.id) as quantity
is betterjoins
produces INNER JOIN
, but you probably want to use LEFT OUTER JOIN
GROUP BY
is not specifiedFor Ruby on Rails >= 5 you use:
categories = Category.select('categories.id, count(items.id) as quantity').
left_outer_joins(:items).
group(:id)
category = categories.first
category.id #=> 12
category.quantity #=> 34
For Ruby on Rails < 5 you replace left_outer_joins(:items)
with:
joins('left outer join items on items.category_id = categories.id')
A Note About to_sql
It may be helpful to know you can call to_sql
on Relation
to view the SQL which is going to be run. If you call it against your code you will see:
select id,
count(id) as quantity
from `categories`
inner join `items` ON `items`.`category_id` = `categories`.`id`
Which does not make much sense. And here is what we get after applying the changes:
select categories.id,
count(items.id) as quantity
from `categories`
left outer join `items` ON `items`.`category_id` = `categories`.`id`
group by `categories`.`id`
Upvotes: 1