简体   繁体   中英

Sorting a JSON array of hashes in descending based on Date

My model has a date attribute:

'date'              => { 'type' => 'date'    }

I am querying based on a user_id attribute and displaying the list of results, then I convert it into a JSON array to be returned in the route.

modelObj = Models::Persistence::ModelName.where(:user_id => user_id)
return modelObj.to_json

This gives me an array of hashes, each hash having a date attribute. How can I sort the hashes based on the date? I tried doing a date sort by converting it to to_i but that doesn't work. How can I do a descending sort based on the Date object?

I tried adding .order(:date) after .where so that I don't sort the JSON array. This gives me

NoMethodError: undefined method `__sort_option__' for :date:Symbol

What am I missing? .order(date: :desc) doesn't break but still returns the data in ascending order.

To answer the literal question,

array.sort_by { |item| -item['date'].to_time.to_i }

However, the points raised in comments are very valid - if you can sort it already in SQL, you should do so. (If you want to know about SQL, tag with DBMS. If you want to know about a specific ORM, tag with those instead.)

EDIT: Thanks, Cary - Indeed, OP wanted the reverse sort.

It seems that you need this: .order("date DESC"). use order after "where". the first param is your column name,and the second param "DESC" means descend,if you don't write the second param,ruby will do default ascend. (I hope you can understand me...I'm not good at English..)

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