我可以获得具有多个用户的帐户集合:
Account.group('accounts.id HAVING count(users.id) > 1').joins(:users)
但是,一旦我在那个对象上调用 .count ,我就会得到一个巨大的爆炸:
(0.3ms) SELECT COUNT(*) AS count_all, accounts.id HAVING count(users.id) > 1 AS accounts_id_having_count_users_id_1 FROM "accounts" INNER JOIN "users" ON "users"."account_id" = "accounts"."id " GROUP BY accounts.id HAVING count(users.id) > 1 ActiveRecord::StatementInvalid: PG::Error: ERROR: 在“AS”第 1 行或附近出现语法错误:...unt_all, accounts.id HAVING count(users .id) > 1 个 AS 帐户...
似乎在 postgres 中,我想要的实际查询是:
select count(*) from (SELECT accounts.id FROM "accounts" INNER JOIN "users" ON "users"."account_id" = "accounts"."id" GROUP BY accounts.id HAVING count(users.id) > 1) as a;
如何获得 activerecord 来生成这个(或类似的)查询?