RubyonRails3:如何根据另一个表的属性对ActiveRecords进行排序?

RubyonRails3:如何根据另一个表的属性对ActiveRecords进行排序?,activerecord,join,ruby-on-rails-3.1,Activerecord,Join,Ruby On Rails 3.1,我需要查询一个数据库表,并获得按关联计数排序的行。有没有Rails(如活动记录查询)的方法来实现这一点 我的模型及其关联如下: class User < ActiveRecord::Base has_one :business end class Business < ActiveRecord::Base has_many :postulations end class Postulation < ActiveRecord::Base belongs_to :busines

我需要查询一个数据库表,并获得按关联计数排序的行。有没有Rails(如活动记录查询)的方法来实现这一点

我的模型及其关联如下:

class User < ActiveRecord::Base
has_one :business
end

class Business < ActiveRecord::Base
has_many :postulations
end

class Postulation < ActiveRecord::Base
belongs_to :business
end
class用户
我需要根据他们的业务假设的数量来获得一些用户的订单。有没有一种干净的方法可以做到这一点,或者我只需要使用find_by_sql查询就可以了

多谢各位

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

这可能会奏效

太好了!我明天会试试,然后告诉你。我不知道包含函数。是的,成功了!谢谢我最终需要一些不同的东西(不得不添加另一个限制),但在你的帮助下我成功地做到了。includes函数非常有用!