Group rail records by created_at dates

So, I have a model that I want to get for recording and group by created_at field dates. But created_at is a datetime field, and I'm only interested in part of the date. So I'm looking for something like a 2D array, the first layer will be a hash with a date string as a key, the second layer will be an array with entries. How can I do it?

  {
 "9/28/2012" => [record, record, record],
 "9/29/2012" => [record, record, record],
 "9/30/2012" => [record, record, record]
 }

At the top of the above, how do I do this if I want the above organization to be applied to all records derived from this model?

+4
source share
1 answer

The ActiveRecord group method will do what you need. In your case, the problem would be to use created_at , which is a date-time, and your restriction for grouping by date. Because date-time dates for dates are database dependent, the code must also be database specific.

For MySql you can:

 Model.group("date(table_name.created_at)") 

For SQLite, you can:

 Model.group("strftime('%Y-%m-%d', table_name.created_at)") 

And for PostgreSQL:

 Model.group("table_name.created_at::date") 

This code, unfortunately, will not be portable, but it may not matter to you. If so, you can always create a shell method that selects the correct conversion syntax based on your DBMS.

+6
source

Source: https://habr.com/ru/post/1436999/


All Articles