Sort array returned by ActiveRecord by date (or any other column)

Ruby on-RailsRubyArraysActiverecord

Ruby on-Rails Problem Overview


How can I sort an array returned by an ActiveRecord query by a created_at date column?

This occurs once the query has been executed.

Please don't tell me to do it in the query because I need this to happen in the view.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Ruby includes support for sorting out of the box.

sorted = @records.sort_by &:created_at

However, this doesn't appear to have much to do with display and probably belongs in the controller.

Solution 2 - Ruby on-Rails

While Ruby Enumerable is awesome, ActiveRecord queries will actually return an ActiveRecord::Relation whose query will not have been evaluated yet (Lazy Loading) and can have the order method called on it to off-load this processing to the database where it will scale much better than an Enumerable based strategy.

Using Enumerable for sorting also confounds doing pagination in the database. There is nothing to prevent the order strategy from being applied in the view. However, I would tend to put this in scope on the model.

sorted = @records.order(:created_at)

Solution 3 - Ruby on-Rails

Just call sort on the collection, passing in the block of code which tells Ruby how you want it to sort:

collection.sort { |a,b| a.created_at <=> b.created_at }

Solution 4 - Ruby on-Rails

Please look at this one and also check complexities.

Model.all.sort_by{|m| m.created_at} #=> O(log n)

#versus

Model.order(“created_at DESC”) #=> O(1)

Solution 5 - Ruby on-Rails

The best way sorting ActiveRecord array is using default method order

> @users.order(:created_at)

It's the quickest and the most right solution, because in that case it returns sorted array from db and you no need to use any other operation for that in the Class, for example if you will use suggested sort_by it will loop throw each element of array, and after that it won't be an ActiveRecord array, not cool in my opinion.

order can use strings and sumbols, it's very useful, and it takes multiple parameters > @users.order('created_at asc, first_name desc, last_name asc')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser94154View Question on Stackoverflow
Solution 1 - Ruby on-RailsChuckView Answer on Stackoverflow
Solution 2 - Ruby on-RailsshulmangView Answer on Stackoverflow
Solution 3 - Ruby on-RailsBill DView Answer on Stackoverflow
Solution 4 - Ruby on-RailsSajjad MurtazaView Answer on Stackoverflow
Solution 5 - Ruby on-RailsDmitriy GusevView Answer on Stackoverflow