Skip to content

Commit

Permalink
Merge pull request #50382 from summera/polymorphic-multi-db-preload-fix
Browse files Browse the repository at this point in the history
Fix multi-database polymorphic preloading with equivalent table names
  • Loading branch information
byroot committed Jan 11, 2024
2 parents c6ef898 + def54b2 commit c5f3a81
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
Expand Up @@ -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)
Expand Down
30 changes: 29 additions & 1 deletion activerecord/test/cases/associations_test.rb
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit c5f3a81

Please sign in to comment.