Created
September 13, 2012 20:03
-
-
Save jswanner/3717188 to your computer and use it in GitHub Desktop.
ActiveRecord Postgres Nulls Last
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This guy (http://stackoverflow.com/users/4219209/lanny-bose) described caveat here: http://stackoverflow.com/questions/5826210/rails-order-with-nulls-last. Could it be the reason?
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
+1 Any heads up on this ? I'd love to see this on Arel.