如果我有3个型号:
模型Section
模型User
has_many :votes
模型Vote
belongs_to :user
并在模型Section
has_many :users
has_many :votes, :through => :users
如何使用AR
关联获得按投票数量排序的章节列表?
答案 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(*)')