1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

infer references from Relation#order

This commit is contained in:
Jon Leighton 2012-01-14 21:28:57 +00:00
parent a84a20e1cd
commit 46ea4442f3
2 changed files with 28 additions and 2 deletions

View file

@ -106,8 +106,14 @@ module ActiveRecord
def order(*args) def order(*args)
return self if args.blank? 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 = clone
relation.order_values += args.flatten relation = relation.references(references) if references.any?
relation.order_values += args
relation relation
end end

View file

@ -1176,17 +1176,37 @@ class RelationTest < ActiveRecord::TestCase
assert !scope.eager_loading? assert !scope.eager_loading?
end end
def test_automatically_added_references def test_automatically_added_where_references
scope = Post.where(:comments => { :body => "Bla" }) scope = Post.where(:comments => { :body => "Bla" })
assert_equal ['comments'], scope.references_values assert_equal ['comments'], scope.references_values
scope = Post.where('comments.body' => 'Bla') scope = Post.where('comments.body' => 'Bla')
assert_equal ['comments'], scope.references_values assert_equal ['comments'], scope.references_values
end
def test_automatically_added_having_references
scope = Post.having(:comments => { :body => "Bla" }) scope = Post.having(:comments => { :body => "Bla" })
assert_equal ['comments'], scope.references_values assert_equal ['comments'], scope.references_values
scope = Post.having('comments.body' => 'Bla') scope = Post.having('comments.body' => 'Bla')
assert_equal ['comments'], scope.references_values assert_equal ['comments'], scope.references_values
end 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 end