Need ruby on rails equivalent query for this sql query -->
SELECT posts.title, comment_count.count FROM posts
INNER JOIN (SELECT post_id, COUNT(*) AS count FROM comments GROUP BY post_id)
AS comment_count ON comment_count.post_id = posts.id
ORDER BY count DESC LIMIT 5;
or
SELECT posts.title, comment_count.count FROM posts
JOIN (SELECT post_id, COUNT(*) AS count FROM comments GROUP BY post_id)
AS comment_count ON c开发者_运维问答omment_count.post_id = posts.id
ORDER BY count DESC LIMIT 5;
In this case you're probably better off by-passing ActiveRecord and just invoking that query via your native driver and getting back just an array or a Hash.
sql = <<-SQL
SELECT posts.title, comment_count.count FROM posts
INNER JOIN (SELECT post_id, COUNT(*) AS count FROM comments GROUP BY post_id)
AS comment_count ON comment_count.post_id = posts.id
ORDER BY count DESC LIMIT 5;
SQL
posts = Post.connection.select_rows(sql)
posts
is now an array of Hashes
精彩评论