.group and .count
suggest changeWe 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"
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents