Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

active record query depending on count of associated objects

I have two models Company and Role related by has_many and belongs_to association respectively. I need to fetch a company that has exactly 'n' number of roles.

I came up with

Company.joins(:roles).having("'count(roles.id) = ?', 3")

but this does not work. Is there an active record solution to this ?

Thanks.

like image 702
prasvin Avatar asked Dec 04 '22 18:12

prasvin


2 Answers

Associations -

role belongs_to :company

company has_many :roles

So, selection for criteria would be -

Company.joins(:roles).group(:company_id).having('count(company_id)= ?', 3)

OR

Company.joins(:roles).group(:company_id).having('count(*)= ?', 3)
like image 137
Sandip Ransing Avatar answered Dec 10 '22 10:12

Sandip Ransing


I know this is not the answer you're looking for, but the best (in terms of performance) solution is to add a simple roles_count column to the companies table, and then add :counter_cache => true onto the belongs_to association declaration. Rails takes care of updating that column for you.

Then,

Company.where("roles_count = ?", 3)

More information: http://guides.rubyonrails.org/association_basics.html#belongs_to-counter_cache

like image 32
bricker Avatar answered Dec 10 '22 10:12

bricker