Ruby on rails Rails 4中的嵌套SQL选择
我正在寻找一种在Rails中生成以下SQL的方法(使其成为一个作用域),这样我就可以将其与其他SQL链接起来(例如,Ruby on rails Rails 4中的嵌套SQL选择,ruby-on-rails,ruby-on-rails-4,rails-activerecord,Ruby On Rails,Ruby On Rails 4,Rails Activerecord,我正在寻找一种在Rails中生成以下SQL的方法(使其成为一个作用域),这样我就可以将其与其他SQL链接起来(例如,Article.published.most_comments): 我尝试了一些类似于Article.joins(:comments)的方法。选择('*').group('comments.Article_id'),但这并没有生成所需的SQL: SELECT * FROM "articles" INNER JOIN "comments" ON "comments"."article
Article.published.most_comments
):
我尝试了一些类似于Article.joins(:comments)的方法。选择('*').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
而且似乎没有一个。从方法中,我可以指定嵌套的SQL SELECT。实际上,有一个:
不确定这是否是最好的方法,但它是有效的
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
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')
}