How can I count the result of an ActiveRecord .group query? Chaining .count returns a hash

前端 未结 6 1219
萌比男神i
萌比男神i 2021-01-08 00:51

I can use the following :

User.where(\"zip_code = \'48104\'\").group(\'users.id\').count

To get hashes like :

{195=>1, 1         


        
6条回答
  •  误落风尘
    2021-01-08 01:08

    As said before by orourkedd the accepted answer is not great when dealing with a large amount of records. I too recently encountered this issue and have large tables that I definitely don't want to load into memory. So here is what works for me.

    users=User.where("zip_code = '48104'").group('users.id')
    user_count=User.where(id: users.select(:id)).count
    

    Rails will handle the users.select part like a subquery. This works with Rails 4

提交回复
热议问题