diff options
author | Jon Leighton <j@jonathanleighton.com> | 2012-01-14 21:28:57 +0000 |
---|---|---|
committer | Jon Leighton <j@jonathanleighton.com> | 2012-01-16 21:17:18 +0000 |
commit | 46ea4442f3abc33d15e03487bae1c80346eab49a (patch) | |
tree | 7aef0835c456052e9d03823d9ae90a9b38738e4e /activerecord | |
parent | a84a20e1cd2133932dd1bd33f862aa2605cc821e (diff) | |
download | rails-46ea4442f3abc33d15e03487bae1c80346eab49a.tar.gz rails-46ea4442f3abc33d15e03487bae1c80346eab49a.tar.bz2 rails-46ea4442f3abc33d15e03487bae1c80346eab49a.zip |
infer references from Relation#order
Diffstat (limited to 'activerecord')
-rw-r--r-- | activerecord/lib/active_record/relation/query_methods.rb | 8 | ||||
-rw-r--r-- | activerecord/test/cases/relations_test.rb | 22 |
2 files changed, 28 insertions, 2 deletions
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index 75369513e3..b5f202ef6a 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -106,8 +106,14 @@ module ActiveRecord def order(*args) return self if args.blank? + args = args.flatten + references = args.reject { |arg| Arel::Node === arg } + .map { |arg| arg =~ /^([a-zA-Z]\w*)\.(\w+)/ && $1 } + .compact + relation = clone - relation.order_values += args.flatten + relation = relation.references(references) if references.any? + relation.order_values += args relation end diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index d8599b1e6d..6d75f31f35 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -1176,17 +1176,37 @@ class RelationTest < ActiveRecord::TestCase assert !scope.eager_loading? end - def test_automatically_added_references + def test_automatically_added_where_references scope = Post.where(:comments => { :body => "Bla" }) assert_equal ['comments'], scope.references_values scope = Post.where('comments.body' => 'Bla') assert_equal ['comments'], scope.references_values + end + def test_automatically_added_having_references scope = Post.having(:comments => { :body => "Bla" }) assert_equal ['comments'], scope.references_values scope = Post.having('comments.body' => 'Bla') assert_equal ['comments'], scope.references_values end + + def test_automatically_added_order_references + scope = Post.order('comments.body') + assert_equal ['comments'], scope.references_values + + scope = Post.order('comments.body', 'yaks.body') + assert_equal ['comments', 'yaks'], scope.references_values + + # Don't infer yaks, let's not go down that road again... + scope = Post.order('comments.body, yaks.body') + assert_equal ['comments'], scope.references_values + + scope = Post.order('comments.body asc') + assert_equal ['comments'], scope.references_values + + scope = Post.order('foo(comments.body)') + assert_equal [], scope.references_values + end end |