diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 59190f35e9..5b31f820c4 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,9 @@ +* Fix regression bug that caused ignoring additional conditions for preloading has_many-through relations. + + Fixes #43132 + + *Alexander Pauly* + * Fix `has_many` inversing recursion on models with recursive associations. *Gannon McGibbon* diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb index 27cc1d099d..45e04dca0d 100644 --- a/activerecord/lib/active_record/associations/preloader/association.rb +++ b/activerecord/lib/active_record/associations/preloader/association.rb @@ -263,7 +263,7 @@ module ActiveRecord end def reflection_scope - @reflection_scope ||= reflection.join_scopes(klass.arel_table, klass.predicate_builder, klass).inject(&:merge!) || klass.unscoped + @reflection_scope ||= reflection.join_scopes(klass.arel_table, klass.predicate_builder, klass).inject(klass.unscoped, &:merge!) end def build_scope diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb index dad67c383e..6b88fd09e5 100644 --- a/activerecord/test/cases/associations_test.rb +++ b/activerecord/test/cases/associations_test.rb @@ -428,6 +428,18 @@ class PreloaderTest < ActiveRecord::TestCase end end + def test_preload_for_hmt_with_conditions + post = posts(:welcome) + _normal_category = post.categories.create!(name: "Normal") + special_category = post.special_categories.create!(name: "Special") + + preloader = ActiveRecord::Associations::Preloader.new(records: [post], associations: :hmt_special_categories) + preloader.call + + assert_equal 1, post.hmt_special_categories.length + assert_equal [special_category], post.hmt_special_categories + end + def test_preload_groups_queries_with_same_scope book = books(:awdr) post = posts(:welcome) diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index 15a82f3079..35e6a1016e 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -114,6 +114,7 @@ class Post < ActiveRecord::Base has_many :category_posts, class_name: "CategoryPost" has_many :scategories, through: :category_posts, source: :category + has_many :hmt_special_categories, -> { where.not(name: nil) }, through: :category_posts, source: :category, class_name: "SpecialCategory" has_and_belongs_to_many :categories has_and_belongs_to_many :special_categories, join_table: "categories_posts", association_foreign_key: "category_id"