简体   繁体   中英

How do I query amount of child records in Ruby on Rails

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?

There are multiple problems:

  • id, count(id) as quantity is ambiguous, categories.id, count(items.id) as quantity is better
  • joins produces INNER JOIN , but you probably want to use LEFT OUTER JOIN
  • GROUP BY is not specified

For 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`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM