Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
@olivierlacan

This comment has been minimized.

Copy link

olivierlacan commented Aug 15, 2013

Is there anything that prevents this from being implement in AR? Is it just the fact that SQLite doesn't seem to support this like PostgreSQL and MySQL (albeit differently) do?

@haggen

This comment has been minimized.

Copy link

haggen commented Apr 22, 2014

+1 Any heads up on this ? I'd love to see this on Arel.

@oduserdnov

This comment has been minimized.

Copy link

oduserdnov commented Jun 3, 2016

@lavilet

This comment has been minimized.

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
You can’t perform that action at this time.