Rails: Order with nulls last

后端 未结 10 1473
悲哀的现实
悲哀的现实 2020-11-30 19:12

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 recor

10条回答
  •  时光取名叫无心
    2020-11-30 20:06

    For posterity's sake, I wanted to highlight an ActiveRecord error relating to NULLS FIRST.

    If you try to call:

    Model.scope_with_nulls_first.last
    

    Rails will attempt to call reverse_order.first, and reverse_order is not compatible with NULLS LAST, as it tries to generate the invalid SQL:

    PG::SyntaxError: ERROR:  syntax error at or near "DESC"
    LINE 1: ...dents"  ORDER BY table_column DESC NULLS LAST DESC LIMIT...
    

    This was referenced a few years ago in some still-open Rails issues (one, two, three). I was able to work around it by doing the following:

      scope :nulls_first, -> { order("table_column IS NOT NULL") }
      scope :meaningfully_ordered, -> { nulls_first.order("table_column ASC") }
    

    It appears that by chaining the two orders together, valid SQL gets generated:

    Model Load (12.0ms)  SELECT  "models".* FROM "models"  ORDER BY table_column IS NULL DESC, table_column ASC LIMIT 1
    

    The only downside is that this chaining has to be done for each scope.

提交回复
热议问题