Skip to content

Commit

Permalink
Merge pull request #14834 from al2o3cr/issue14155
Browse files Browse the repository at this point in the history
Correctly alias table names when joining more than once
  • Loading branch information
tenderlove authored and rafaelfranca committed May 27, 2014
1 parent 030ef7c commit 569136b
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
12 changes: 11 additions & 1 deletion activerecord/lib/active_record/associations/alias_tracker.rb
Expand Up @@ -32,8 +32,18 @@ def self.initial_count_for(connection, name, table_joins)
join.left.downcase.scan( join.left.downcase.scan(
/join(?:\s+\w+)?\s+(\S+\s+)?#{quoted_name}\son/ /join(?:\s+\w+)?\s+(\S+\s+)?#{quoted_name}\son/
).size ).size
else elsif join.respond_to? :left
join.left.table_name == name ? 1 : 0 join.left.table_name == name ? 1 : 0
else
# this branch is reached by two tests:
#
# activerecord/test/cases/associations/cascaded_eager_loading_test.rb:37
# with :posts
#
# activerecord/test/cases/associations/eager_test.rb:1133
# with :comments
#
0
end end
end end


Expand Down
11 changes: 10 additions & 1 deletion activerecord/lib/active_record/relation/finder_methods.rb
Expand Up @@ -323,7 +323,16 @@ def raise_record_not_found_exception!(ids, result_size, expected_size) #:nodoc:
private private


def find_with_associations def find_with_associations
join_dependency = construct_join_dependency # NOTE: the JoinDependency constructed here needs to know about
# any joins already present in `self`, so pass them in
#
# failing to do so means that in cases like activerecord/test/cases/associations/inner_join_association_test.rb:136
# incorrect SQL is generated. In that case, the join dependency for
# SpecialCategorizations is constructed without knowledge of the
# preexisting join in joins_values to categorizations (by way of
# the `has_many :through` for categories).
#
join_dependency = construct_join_dependency(joins_values)


aliases = join_dependency.aliases aliases = join_dependency.aliases
relation = select aliases.columns relation = select aliases.columns
Expand Down
Expand Up @@ -126,4 +126,14 @@ def test_find_with_conditions_on_through_reflection
categories = author.categories.includes(:special_categorizations).references(:special_categorizations).to_a categories = author.categories.includes(:special_categorizations).references(:special_categorizations).to_a
assert_equal 2, categories.size assert_equal 2, categories.size
end end

test "the correct records are loaded when including an aliased association" do
author = Author.create! name: "Jon"
author.categories.create! name: 'Not Special'
author.special_categories.create! name: 'Special'

categories = author.categories.eager_load(:special_categorizations).order(:name).to_a
assert_equal 0, categories.first.special_categorizations.size
assert_equal 1, categories.second.special_categorizations.size
end
end end

0 comments on commit 569136b

Please sign in to comment.