ruby on rails - Sum of associations count by single sql query -


there 2 models:

class category < activerecord::base   has_and_belongs_to_many :items end  class item < activerecord::base   has_and_belongs_to_many :categories end 

i've got array category ids. there way total items count belong categories array single sql query?

first let's items in categories want array:

item.joins(:categories).where(categories: {id: category_ids}) 

then lets count each category

item.joins(:categories).where(categories: {id: category_ids}).uniq.count 

Comments