Arel:按关联计数排序 [英] Arel: order by association count

查看:55
本文介绍了Arel:按关联计数排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我想要做的

class Question
  has_many :votes
end

class Vote
  belongs_to :question
end

我想找到按投票数排序的所有问题.我想在不使用任何计数器缓存的情况下在 Arel(在 Rails 3 中)表达这一点.

I want to find all questions ordered by the number of votes they have. I want to express this in Arel (in Rails 3) without using any counter caches.

有没有办法做到这一点?

Is there any way of doing this ?

谢谢.

推荐答案

试试这个:

Question.select("questions.*, a.vote_count AS vote_count").
 joins("LEFT OUTER JOIN (
    SELECT b.question_id, COUNT(b.id) AS vote_count
    FROM   votes b
    GROUP BY b.question_id
  ) a ON a.question_id = questions.id")

解决方案与数据库无关.确保在 votes 表的 question_id 列上添加索引(即使您不使用此解决方案,也应该添加索引).

Solution is DB agnostic. Make sure you add an index on the question_id column in the votes table( you should add the index even if you don't use this solution).

这篇关于Arel:按关联计数排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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