Reputation: 2066
I need to query a database table and get the rows ordered by a count of an association. Is there a Rails (like Active Record Query) way to do this?
My models and their associations are as follows:
class User < ActiveRecord::Base
has_one :business
end
class Business < ActiveRecord::Base
has_many :postulations
end
class Postulation < ActiveRecord::Base
belongs_to :business
end
I need to get a number of Users ordered by the amount of Postulations that their Business has. Is there a clean way to do this or do I just have to query with find_by_sql?
Thank you.
Upvotes: 2
Views: 231
Reputation: 447
User.includes(:business => :postulations).group("users.id").order("count(postulations.id) desc").limit(20)
This will probably work
Upvotes: 2