【问题标题】:rails 3 getting the count of the records that have more than one associate records (has_many)rails 3 获取具有多个关联记录的记录数(has_many)
【发布时间】:2014-06-11 14:06:48
【问题描述】:

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

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

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    活动记录支持“拥有”作为一种方法。 所以你可以这样查询:

    Account.joins(:users).select('accounts.id').group('accounts.id').having('count(users.id) > 1')
    

    【讨论】:

      【解决方案2】:

      你为什么不从用户模型中尝试这个, 你在哪里 group_by 来自用户模型的 account_id

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

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

      【讨论】:

      • 但这需要 ruby​​ 遍历集合并对每个值进行比较 - 然后调用 count 。我正在寻找一种方法让数据库进行计数。
      猜你喜欢
      • 1970-01-01
      • 2011-02-17
      • 2012-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多