From 6cf4835b743cbce2536d53ae0a4a998f4f0f1e24 Mon Sep 17 00:00:00 2001 From: Eugene Kenny Date: Sun, 26 Feb 2017 23:29:08 +0000 Subject: Allow order to be given expressions as hash keys When `order` is given a hash, the keys are currently assumed to be attribute names and are quoted as such in the query, which makes it impossible to pass an expression instead: Post.order("LENGTH(title)" => :asc).last # SELECT `posts`.* FROM `posts` ORDER BY `posts`.`LENGTH(title)` DESC LIMIT 1 If the key is an `Arel::Nodes::SqlLiteral`, we now use it directly in the query. This provides a way to build a relation with a complex order clause that can still be reversed with `reverse_order` or `last`. --- activerecord/lib/active_record/relation/query_methods.rb | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'activerecord/lib/active_record/relation/query_methods.rb') diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index 4ee413c805..1178dec706 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -1130,7 +1130,12 @@ module ActiveRecord arel_attribute(arg).asc when Hash arg.map { |field, dir| - arel_attribute(field).send(dir.downcase) + case field + when Arel::Nodes::SqlLiteral + field.send(dir.downcase) + else + arel_attribute(field).send(dir.downcase) + end } else arg -- cgit v1.2.3