为了通过的has_many计数:通过对Rails 3项 [英] Order by count of has_many :through items in Rails 3

查看:198
本文介绍了为了通过的has_many计数:通过对Rails 3项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有3个型号:

示范部分

示范用户

的has_many:票

示范投票

belongs_to的:用户

和内部模型部分

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

如何使用 AR 协会通过投票数量排序的章节列出?

How to get the Sections list ordered by votes quantity using the AR associations?

推荐答案

以最合理的方式做到这一点是使用写成原始的SQL子查询订购的结果如下...

The most reasonable way to do this is to use a subquery written as raw SQL for ordering the result as follows...

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

这篇关于为了通过的has_many计数:通过对Rails 3项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆