Ruby on Rails 3: How can I sort ActiveRecords by an attribute of another table?

ⅰ亾dé卋堺 提交于 2019-12-10 10:46:32

问题


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.


回答1:


User.includes(:business => :postulations).group("users.id").order("count(postulations.id) desc").limit(20)

This will probably work



来源:https://stackoverflow.com/questions/7731908/ruby-on-rails-3-how-can-i-sort-activerecords-by-an-attribute-of-another-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!