2016-03-27 78 views
-1

我正在尋找一種方法來生成Rails的下面的SQL(使它成爲一個範圍內),這樣我就可以進一步scopes(如Article.published.most_comments)IT連鎖:嵌套SQL SELECT Rails中4

SELECT *, cs.count 
FROM articles, (
    SELECT article_id, count(*) 
    FROM comments 
    GROUP BY comments.article_id 
) cs 
WHERE articles.id = cs.article_id 
ORDER BY cs.count DESC; 

我試着沿Article.joins(:comments).select('*').group('comments.article_id')線的東西,但是,這並不產生所需的SQL:

SELECT * FROM "articles" 
INNER JOIN "comments" ON "comments"."article_id" = "articles"."id" 
GROUP BY comments.article_id 

(PSQL): PG::GroupingError: ERROR: column "articles.id" 
     must appear in the GROUP BY clause or be used in 
     an aggregate function 

而且似乎沒有成爲一個.from方法中,我可以指定嵌套的SQL SELECT 。

回答

1

其實,有一個.from method

scope :most_comments, -> { 
    Article.select('*, cs.count').from(
    'articles, (
     SELECT article_id, count(*) 
     FROM comments 
     GROUP BY comments.article_id 
    ) cs' 
    ) 
    .where('articles.id = cs.article_id') 
    .order('cs.count DESC') 
} 

不知道這是最好的方式,但它的工作原理...