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

How can I sort the array returned by an ActiveRecord request by the created_at date column?

This happens after the request is completed.

Please do not tell me to do this in the request, because I need this to happen in the view.

+49
arrays ruby ruby-on-rails activerecord
Aug 14 '09 at 15:24
source share
5 answers

Ruby includes support for sorting out of the box.

 sorted = @records.sort_by &:created_at 

However, this does not seem to have much to do with the mapping, and probably belongs to the controller.

+105
Aug 14 '09 at 15:29
source share

While Ruby Enumerable is awesome, ActiveRecord queries will actually return ActiveRecord :: Relation, whose query has not yet been evaluated (Lazy Loading), and may have an ordering method that calls it to disable this processing in the database, where it will scale much better than enumerable strategy.

Using Enumerable for sorting also mixes pagination into the database. There is nothing to prevent the application of an ordering strategy in a view. However, I would try to include this in the model for model.

 sorted = @records.order(:created_at) 
+25
Jan 20 '14 at
source share

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

 collection.sort { |a,b| a.created_at <=> b.created_at } 
+23
Aug 14 '09 at 15:31
source share

Please lure him and also check the difficulty.

 Model.all.sort_by{|m| m.created_at} #=> O(log n) #versus Model.order("created_at DESC") #=> O(1) 
+1
Mar 28 '16 at 11:51
source share

The best way to sort an ActiveRecord array is to use the default method method

@ users.order (: created_at)

This is the fastest and most correct solution, because in this case it returns a sorted array from db, and you do not need to use any other operation for this in the class, for example, if you use the proposed sort_by , it will loop every element array, and after that it will not be an ActiveRecord array, not cool in my opinion.

order can use strings and sumbols, it is very useful, and several parameters are required

@ users.order ('created_at asc, first_name desc, last_name asc')

0
Feb 10 '17 at 9:15
source share



All Articles