2

This SO question How do I group by day instead of date? shows how to group in Ruby.

This works, but is going to be very slow for a large number of records. How to do it so that the grouping and counting by :created_at by day happens within Postgres?

Community
  • 1
  • 1
B Seven
  • 44,484
  • 66
  • 240
  • 385

1 Answers1

6

If you haven't an order scope defined, you can use date() method from postgres, like this:

Post.select("date(created_at) as created_date").group("created_date")

And if you do have an order scope:

Post.all.except(:order).
     select("date(created_at) as created_date").group("created_date")

You will have to define select fields in order to have a custom grouping, so the select() part should contain the fields you need your recordset to contain.

Ruby Racer
  • 5,690
  • 1
  • 26
  • 43