Ruby on Rails - .group and .count in ruby on rails- ruby on rails tutorial - rails guides - rails tutorial - ruby rails
- We have a Product model and we want to group them by their category.
Product.select(:category).group(:category)
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team
This will query the database as follows:
SELECT "product"."category" FROM "product" GROUP BY "product"."category"
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team
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
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team
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"