I can use the following :
User.where(\"zip_code = \'48104\'\").group(\'users.id\').count
To get hashes like :
{195=>1, 1
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