premunk
premunk

Reputation: 423

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.

Upvotes: 0

Views: 1674

Answers (2)

vivian93
vivian93

Reputation: 1

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..)

Upvotes: 0

Amadan
Amadan

Reputation: 198324

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.

Upvotes: 4

Related Questions