[英]Arel: order by association count
这是我想要做的
class Question
has_many :votes
end
class Vote
belongs_to :question
end
我想找到所有有投票权的问题。 我想在Arel中(在Rails 3中)表达它而不使用任何计数器缓存。
有什么办法吗?
谢谢。
尝试下一个:
Question.joins(:votes).select("questions.id, *other question coulmns*, count(votes.id) as vote_count").order("vote_count DESC").group("questions.id")
尝试这个:
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
列上添加索引(即使不使用此解决方案,也应添加索引)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.