Nikolay's Blog

Rails How to Group records by Fields

Cover Image for Rails How to Group records by Fields
  • Created at:

For the statistic purposes .group method can be extrily useful. It groups records by specified field or functions and can apply following aggregate functions:

Group by Count

  • Count users by their statuses:
User
  .group(:status)
  .count

# => { 'approved' => 7, 'verified' => 12, 'banned' => 1 }

Group by Date

It can group by date/month/day

  • Get amount of sellings per day:
CompletedOrder
  .group("date(created_at)")
  .pluck("date(created_at) as ordered_at, sum(price) as total_price")

Group by Multiply Fields

Get amount of completed orders per users:

User
  .left_joins(:completed_orders)
  .group('users.id')
  .having('COUNT(completed_orders.id) > 0')
  .pluck('users.id', 'COUNT(completed_orders.id)')