.group and .count

suggest change

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

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

This queries the database as follows. The table name is the plural products:

SELECT "products"."category" FROM "products" GROUP BY "products"."category"

Select the grouped column as well. Grouping is especially useful for counting categories in the database, which is more efficient than loading every row and counting in Ruby. count(:category) returns a hash of category to count:

Product.group(:category).count(:category)
SELECT COUNT("products"."category") AS count_categories, "products"."category" AS products_category FROM "products" GROUP BY "products"."category"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents