Ruby on Rails ActiveRecord Query Interface .group and .count


Example

We have a Product model and we want to group them by their category.

Product.select(:category).group(:category)

This will query the database as follows:

SELECT "product"."category" FROM "product" GROUP BY "product"."category"

Make sure that the grouped field is also selected. Grouping is especially useful for counting the occurrence - in this case - of categories.

Product.select(:category).group(:category).count

As the query shows, it will use the database for counting, which is much more efficient, than retrieving all record first and do the counting in the code:

SELECT COUNT("products"."category") AS count_categories, "products"."category" AS products_category FROM "products" GROUP BY "products"."category"