Arel: order by association count

本秂侑毒 提交于 2019-12-23 03:37:13

问题


Here is what I'm trying to do

class Question
  has_many :votes
end

class Vote
  belongs_to :question
end

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 ?

Thanks.


回答1:


Try 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")

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




回答2:


Try next one:

Question.joins(:votes).select("questions.id, *other question coulmns*, count(votes.id) as vote_count").order("vote_count DESC").group("questions.id")


来源:https://stackoverflow.com/questions/7391325/arel-order-by-association-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!