Order and sort_by difference in Ruby on Rails ActiveRecord

.sort_by is a Ruby method from Enumerable that is used to sort arrays (or array like objects). Using .sort_by will cause all the records to be loaded from the database into the servers memory, which can lead to serious performance problems (as well as your issue with nil values).

.order is a ActiveRecord method that adds a ORDER BY clause to the SQL select statement. The database will handle sorting the records. This is preferable in 99% of cases.


sort_by is executed in Ruby, so if you have a nil value, things will break in a way similar to this:

[3, nil, 1].sort
#=> ArgumentError: comparison of Fixnum with nil failed

order is executed by your RDBMS, which generally will do fine with NULL values. You can even specify where you want to put the NULL VALUES, by adding NULL FIRST (usually the default) or NULL LAST to your ORDER BY clause?


Hey you needn't you sort in that query, it'll work very long, if you work with DB you should always use :order, there solution for your problem

@item = Item.order('item_timestamp DESC NULLS LAST').paginate(:page => params[:page], :per_page => 5)