Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails 4中的嵌套SQL选择_Ruby On Rails_Ruby On Rails 4_Rails Activerecord - Fatal编程技术网

Ruby on rails Rails 4中的嵌套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

我正在寻找一种在Rails中生成以下SQL的方法(使其成为一个作用域),这样我就可以将其与其他SQL链接起来(例如,
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')
}