Skip to content

Instantly share code, notes, and snippets.

@jswanner
Created September 13, 2012 20:03
Show Gist options
  • Select an option

  • Save jswanner/3717188 to your computer and use it in GitHub Desktop.

Select an option

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)
@olivierlacan

Copy link
Copy Markdown

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

haggen commented Apr 22, 2014

Copy link
Copy Markdown

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

@oduserdnov

Copy link
Copy Markdown

@lavilet

lavilet commented Jun 21, 2016

Copy link
Copy Markdown

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