Order and sort_by difffference in Ruby on Rails ActiveRecord

I am trying to sort my data according to the timestamp field in my controller, note that the timestamp field may be null and may have some value. I wrote the following query.

@item = Item.sort_by(&:item_timestamp).reverse
            .paginate(:page => params[:page], :per_page =>5)

But this gives an error when I have elements that have the time_timestamp field set to NULL, but the following query is executed.

@item = Item.order(:item_timestamp).reverse
            .paginate(:page => params[:page], :per_page => 5)

Can someone tell the difference between the two queries and in what state to use which?

And I use the reverse order to get the last items from the database. Is this the best way or are there other better ways to get the latest data from a database in terms of performance?

+4
source share
3 answers

sort_byruns in Ruby, so if you have a value nil, everything will be broken in the same way:

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

orderperformed by your RDBMS, which will usually be fine with NULL. You can even indicate where you want to place NULL VALUESby adding NULL FIRST(usually the default) or NULL LASTto your proposal ORDER BY?

+5
source

.sort_byis the Ruby method from Enumerable , which is used to sort arrays (or arrays like objects). Using it .sort_bywill cause all records to be loaded from the database into the server memory, which can lead to serious performance problems (as well as your problem with zero values).

.order - ActiveRecord, ORDER BY SQL select. . 99% .

+2

Hey, you don’t need to sort in this query, it will work for a very long time, if you work with a database, you should always use it :order, there is a solution for your problem

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

Source: https://habr.com/ru/post/1671960/


All Articles