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

前端 未结 6 1206
萌比男神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:17

    The accepted answer is not scalable. Using @robbrit's method on a query with 25,000 matching users would pull 25,000 results (ie an array with 25,000 elements) into memory and then count the elements array. Here is a method that will do it without pulling all that data:

    def count_query(query)
      query = "SELECT count(*) AS count_all FROM (#{query.to_sql}) x"
      ActiveRecord::Base.connection.execute(query).first.try(:[], 0).to_i
    end
    

    It is used like this:

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

    This works for me using mysql, btw.

    It was inspired by this guy: https://github.com/mrbrdo/active_record_group_count/blob/master/lib/active_record_group_count/scope.rb

提交回复
热议问题