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).