So I've found these questions:
- How to group and count by day in Rails in Postgres?
- Grouping by week/month/etc & ActiveRecord?
- How do I group by day instead of date?
And this gem: https://github.com/ankane/groupdate
I'm looking to group records by day, in a format like this:
[
{ "2016-03-16" => [Record1, Record2, Record3] },
{ "2016-03-17" => [Record1, Record2] },
{ "2016-03-18" => [Obj1, Obj2] }
]
I've been able to get this format using this code:
def group_by_criteria
created_at.to_date.to_s
end
list.group_by(&:group_by_criteria).map {|k,v| { k => v} }
However, as explained in other questions, this is not very efficient for a large number of records, I think I should be using grouping from the db, but I'm not sure how to get the format I'm looking for, I tried something like this but I don't get what I'm expecting:
list.order("date_trunc('day', created_at) DESC).map{ |k, v| { k => v }}
How can I group records by day from the db like this?