开发者

Arel: order by association count

开发者 https://www.devze.com 2023-04-04 03:06 出处:网络
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 numb开发者_Go百科er of votes they have. I want to

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 numb开发者_Go百科er 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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消