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
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.