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

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


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.


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)


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 }