Browse files

fix to_sql output on eager loaded relations

  • Loading branch information...
1 parent e43b3e3 commit a9748da24a5643f012fa747c2b6aa957ac7c4ee2 @tenderlove tenderlove committed Jul 2, 2013
Showing with 17 additions and 1 deletion.
  1. +9 −1 activerecord/lib/active_record/relation.rb
  2. +8 −0 activerecord/test/cases/relations_test.rb
View
10 activerecord/lib/active_record/relation.rb
@@ -491,7 +491,15 @@ def reset
# User.where(name: 'Oscar').to_sql
# # => SELECT "users".* FROM "users" WHERE "users"."name" = 'Oscar'
def to_sql
- @to_sql ||= klass.connection.to_sql(arel, bind_values.dup)
+ @to_sql ||= begin
+ if eager_loading?
+ join_dependency = construct_join_dependency
+ relation = construct_relation_for_association_find(join_dependency)
+ klass.connection.to_sql(relation.arel, relation.bind_values)
+ else
+ klass.connection.to_sql(arel, bind_values.dup)
+ end
+ end
end
# Returns a hash of where conditions.
View
8 activerecord/test/cases/relations_test.rb
@@ -480,6 +480,14 @@ def test_loading_with_one_association
assert_equal Post.find(1).last_comment, post.last_comment
end
+ def test_to_sql_on_eager_join
+ expected = assert_sql {
+ Post.eager_load(:last_comment).order('comments.id DESC').to_a
+ }.first
+ actual = Post.eager_load(:last_comment).order('comments.id DESC').to_sql
+ assert_equal expected, actual
+ end
+
def test_loading_with_one_association_with_non_preload
posts = Post.eager_load(:last_comment).order('comments.id DESC')
post = posts.find { |p| p.id == 1 }

0 comments on commit a9748da

Please sign in to comment.