Search code examples
ruby-on-railspostgresqlruby-on-rails-4

Rails 4 - Order by the presence of an attribute


Using Rails 4. Psql DB.

I have a model Article with an attribute amazon_title. I am having trouble understanding how I can order my articles so articles with the amazon_title present are first, and ones without are second.

I've tried ordering them like this with no success:

Article.all.order(amazon_title: :desc)

The above orders it alphabetically, showing blank first, present second, and nil third.


Solution

  • For PostgreSQL (the order will be true, false, nil):

    Article.order('amazon_title DESC NULLS LAST')
    

    Another option (database agnostic):

    Article.order('(CASE WHEN amazon_title THEN 1 WHEN amazon_title IS NULL THEN 2 ELSE 3 END) ASC')