简体   繁体   中英

Ruby on Rails / Active Record / MYSQL - Group by and order by a string attribute

I have a model/object with a date attribute as a string, and this code:

Model.all.group_by { |t| t.date }

This gives me a hash like {"06/11/2013"=>[object 5, object 17], "07/18/2013"=>[...], "05/02/2013"=>[...]} (with all the model's attributes in there).

It doesn't seem to sort by date at all this way. In fact it pretty much jumps around.

Is there a way for me to add an

.order('date ASC')

on here somehow, so that the hash goes in order by date?

if you do

Model.all.group_by{ |t| t.date }.sort

then you will get sorted result but it will be double array. You can convert this array to hash or use accordingly.

You can use T-SQL CAST or CONVERT.

With respect to your database (MySQL?) I think this will work:

Model.all.order('CAST(date AS TIMESTAMP) asc')

or

Model.all.order('CAST(created_at AS DATETIME) asc')

But your string format shall be convertable, otherwise you cannot cast type

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