按has_many的数量排序:通过Rails 3中的项目

时间:2012-07-24 02:21:39

标签: ruby-on-rails-3 count associations has-many-through

如果我有3个型号:

模型Section

模型User

has_many :votes

模型Vote

belongs_to :user

并在模型Section

has_many :users
has_many :votes, :through => :users

如何使用AR关联获得按投票数量排序的章节列表?

2 个答案:

答案 0 :(得分:2)

最合理的方法是使用编写为原始SQL的子查询来按如下方式对结果进行排序...

Section.order(
  '(select count(1) from votes inner join users on votes.user_id=users.id where users.section_id=sections.id)'
)

答案 1 :(得分:0)

Section.joins(users: :votes).group(:id).order('COUNT(*)')