7

我可以获得具有多个用户的帐户集合:

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 来生成这个(或类似的)查询?

4

2 回答 2

12

活动记录支持“拥有”作为一种方法。因此,您可以通过以下方式进行查询:

Account.joins(:users).select('accounts.id').group('accounts.id').having('count(users.id) > 1')
于 2014-06-11T06:06:48.953 回答
0

你为什么不从用户模型中尝试这个,在那里你通过用户模型中的 account_id 分组

User.count(:group => :account_id) 这可能会返回显示 {:account_id => count_of_users } 的哈希,例如 {1 => 3, 2 => 5, 3 => 2}

现在选择用户数大于 1 的 account_id。

于 2013-04-25T04:34:04.533 回答