简体   繁体   中英

How to group records by day in Rails using Postgres

So I've found these questions:

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?

Because you ultimately do want to load all records into memory, your first solution (grouping in Ruby) is actually the best you can do. Leveraging SQL grouping could help optimize if you wanted to just, say, get a count of records in each group, or even a comma-separated list of record names, but -- since you actually want the records -- there's no way to get around the fact you'll simply have to fetch all the records.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM