diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb index 7c23b7fbe2637..4ab8ef0558824 100644 --- a/activerecord/lib/active_record/associations/preloader/association.rb +++ b/activerecord/lib/active_record/associations/preloader/association.rb @@ -17,11 +17,12 @@ def initialize(scope, association_key_name) def eql?(other) association_key_name == other.association_key_name && scope.table_name == other.scope.table_name && + scope.connection_specification_name == other.scope.connection_specification_name && scope.values_for_queries == other.scope.values_for_queries end def hash - [association_key_name, scope.table_name, scope.values_for_queries].hash + [association_key_name, scope.table_name, scope.connection_specification_name, scope.values_for_queries].hash end def records_for(loaders) diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb index 074a775a36959..a05cbe122ea87 100644 --- a/activerecord/test/cases/associations_test.rb +++ b/activerecord/test/cases/associations_test.rb @@ -39,6 +39,8 @@ require "models/cpk" require "models/member_detail" require "models/organization" +require "models/dog" +require "models/other_dog" class AssociationsTest < ActiveRecord::TestCase @@ -773,7 +775,8 @@ def test_associations_raise_with_name_error_if_associated_to_classes_that_do_not class PreloaderTest < ActiveRecord::TestCase fixtures :posts, :comments, :books, :authors, :tags, :taggings, :essays, :categories, :author_addresses, :sharded_blog_posts, :sharded_comments, :sharded_blog_posts_tags, :sharded_tags, - :members, :member_details, :organizations, :cpk_orders, :cpk_order_agreements + :members, :member_details, :organizations, :cpk_orders, :cpk_order_agreements, + :dogs, :other_dogs def test_preload_with_scope post = posts(:welcome) @@ -1206,6 +1209,31 @@ def test_preload_does_not_group_same_scope_different_key_name end end + def test_multi_database_polymorphic_preload_with_same_table_name + dog = dogs(:sophie) + dog_comment = comments(:greetings) + dog_comment.origin_type = dog.class.name + dog_comment.origin_id = dog.id + + other_dog = other_dogs(:lassie) + other_dog_comment = comments(:more_greetings) + other_dog_comment.origin_type = other_dog.class.name + other_dog_comment.origin_id = other_dog.id + + # Both Dog and OtherDog are backed by a table named `dogs`, + # however they are stored in different databases and should + # therefore result in two separate queries rather than be batched + # together. + # + # Expected + # SELECT FROM dogs ... (Dog) + # SELECT FROM dogs ... (OtherDog) + assert_queries(2) do + preloader = ActiveRecord::Associations::Preloader.new(records: [dog_comment, other_dog_comment], associations: :origin) + preloader.call + end + end + def test_preload_with_available_records post = posts(:welcome) david = authors(:david)