Rails ActiveRecord count on groups
Rails ActiveRecord can count queries with GROUP BY
clauses, and in this case the result is not just an integer, but a Hash with the grouped values and the count for each group. Check this out:
Project.group(:status, :city).count
# SELECT COUNT(*) AS count_all, "projects"."status" AS projects_status, "projects"."city" AS projects_city
# FROM "projects"
# GROUP BY "projects"."status", "projects"."city"
=> {
[:pending, "Jacksonville Beach"] => 21,
[:finished, "Jacksonville Beach"] => 1061
[:pending, "Chicago"] => 10,
[:finished, "Chicago"] => 980,
}
So rails manipulates the select statement to have all grouped by fields and the count(*)
as well, which is pretty neat.