Search code examples
ruby-on-railsruby-on-rails-3sortingactiverecordnull

Rails: Order with nulls last


In my Rails app I've run into an issue a couple times that I'd like to know how other people solve:

I have certain records where a value is optional, so some records have a value and some are null for that column.

If I order by that column on some databases the nulls sort first and on some databases the nulls sort last.

For instance, I have Photos which may or may not belong to a Collection, ie there are some Photos where collection_id=nil and some where collection_id=1 etc.

If I do Photo.order('collection_id desc) then on SQLite I get the nulls last but on PostgreSQL I get the nulls first.

Is there a nice, standard Rails way to handle this and get consistent performance across any database?


Solution

  • Adding arrays together will preserve order:

    @nonull = Photo.where("collection_id is not null").order("collection_id desc")
    @yesnull = Photo.where("collection_id is null")
    @wanted = @nonull+@yesnull
    

    http://www.ruby-doc.org/core/classes/Array.html#M000271