我可以获得拥有多个用户的帐户集合:
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 ::错误:错误:“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来生成此(或类似的)查询?
答案 0 :(得分:10)
活动记录支持'有'作为方法。 所以你可以用这种方式进行查询:
Account.joins(:users).select('accounts.id').group('accounts.id').having('count(users.id) > 1')
答案 1 :(得分:0)
为什么不从User模型中尝试这个, 你在哪里分组来自用户模型的account_id
User.count(:group => :account_id)
这可能会返回显示{:account_id => count_of_users}
例如,{1 => 3,2 => 5,3 => 2}
现在选择用户数大于1的account_id。