Ruby on Rails ActiveRecord Query Interface .group and .count

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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"


Got any Ruby on Rails Question?