From 019583e939f6615590a4d6c1e4370e4e973fedff Mon Sep 17 00:00:00 2001 From: Ryuta Kamizono Date: Tue, 24 Oct 2017 21:47:11 +0900 Subject: [PATCH] Ensure associations doesn't table name collide with aliased joins Currently alias tracker only refer a table name, doesn't respect an alias name. Should use `join.left.name` rather than `join.left.table_name`. --- .../lib/active_record/associations/alias_tracker.rb | 2 +- .../cases/associations/inner_join_association_test.rb | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/associations/alias_tracker.rb b/activerecord/lib/active_record/associations/alias_tracker.rb index 6bac5fd3f5..07bd0a273b 100644 --- a/activerecord/lib/active_record/associations/alias_tracker.rb +++ b/activerecord/lib/active_record/associations/alias_tracker.rb @@ -31,7 +31,7 @@ module ActiveRecord /JOIN(?:\s+\w+)?\s+(?:\S+\s+)?(?:#{quoted_name}|#{name})\sON/i ).size elsif join.respond_to? :left - join.left.table_name == name ? 1 : 0 + join.left.name == name ? 1 : 0 elsif join.is_a?(Hash) join[name] else diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb index eb85acf37e..7be875fec6 100644 --- a/activerecord/test/cases/associations/inner_join_association_test.rb +++ b/activerecord/test/cases/associations/inner_join_association_test.rb @@ -37,6 +37,14 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase assert_match(/agents_people_2/i, sql) end + def test_construct_finder_sql_does_not_table_name_collide_with_aliased_joins + people = Person.arel_table + agents = people.alias("agents_people") + constraint = agents[:primary_contact_id].eq(people[:id]) + sql = Person.joins(:agents).joins(agents.create_join(agents, agents.create_on(constraint))).to_sql + assert_match(/agents_people_2/i, sql) + end + def test_construct_finder_sql_ignores_empty_joins_hash sql = Author.joins({}).to_sql assert_no_match(/JOIN/i, sql)