我有如下查询:
Author.select('authors.*, max(books.published_at) as last_publishing')
.joins(:books)
.group('authors.id')
这就是我想要的(返回用最近发布日期注释的作者列表),但是如果我尝试对此查询调用count,则会出现问题。
SELECT COUNT(authors.*, max(books.published_at) as last_publishing)
AS count_authors_all_max_books_published_at_as_last_publishing, authors.id
AS authors_id FROM "authors"
INNER JOIN "books"
ON "books"."author_id" = "authors"."id"
GROUP BY authors.id
*** ActiveRecord::StatementInvalid Exception: PG::SyntaxError: ERROR: syntax error at or near "as"
LINE 1: ...COUNT(authors.*, max(books.published_at) as last_pu...
显然这不是我想要生成的SQL - 我只想要一个SELECT COUNT(*)FROM()myQuery。
我看到有a similar issue with Rails 4 - 还有其他人反对这个/是否有解决方法?我可以做query.to_a.size,但我更愿意能够为我和我的同事使用count方法,未来的理智。
答案 0 :(得分:0)
您应该在呼叫计数
之前删除select temporaryauthors = Author.select('authors.*, max(books.published_at) as last_publishing')
.joins(:books)
.group('authors.id')
total_authors = authors.except([:includes]).count(:all)