Skip to content

Instantly share code, notes, and snippets.

@jswanner
Created September 13, 2012 20:03
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jswanner/3717188 to your computer and use it in GitHub Desktop.
Save jswanner/3717188 to your computer and use it in GitHub Desktop.
ActiveRecord Postgres Nulls Last
ActiveSupport.on_load(:active_record) do
module Arel::NullsLastPredications
def nulls_last
Arel::Nodes::NullsLast.new self
end
end
module Arel::Nodes
class NullsLast < Unary
def gsub *args
expr.to_sql.gsub *args
end
end
Ordering.send(:include, Arel::NullsLastPredications)
end
module Arel::Visitors
class DepthFirst
private
alias :visit_Arel_Nodes_NullsLast :unary
end
class PostgreSQL
private
def visit_Arel_Nodes_NullsLast o
"#{visit o.expr} NULLS LAST"
end
end
end
end
#Sample use:
users = User.arel_table
User.order(users[:first_name].desc.nulls_last)
@lavilet
Copy link

lavilet commented Jun 21, 2016

If someone want the above snippet to work in Rails > 4 and Arel v. 6 change the visit_Arel_Nodes_NullsLast method in PostgreSQL class to:

      def visit_Arel_Nodes_NullsLast o, collector
        (visit o.expr, collector) << ' NULLS LAST'
      end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment