问题
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