Skip to content

Commit 017f727

Browse files
committed
Fix preloading for hmt relations with conditions
1 parent fbdb22b commit 017f727

File tree

4 files changed

+20
-1
lines changed

4 files changed

+20
-1
lines changed

activerecord/CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
* Fix regression bug that caused ignoring additional conditions for preloading has_many-through relations.
2+
3+
Fixes #43132
4+
5+
*Alexander Pauly*
6+
17
* Fix `has_many` inversing recursion on models with recursive associations.
28

39
*Gannon McGibbon*

activerecord/lib/active_record/associations/preloader/association.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,7 @@ def owner_key_type
263263
end
264264

265265
def reflection_scope
266-
@reflection_scope ||= reflection.join_scopes(klass.arel_table, klass.predicate_builder, klass).inject(&:merge!) || klass.unscoped
266+
@reflection_scope ||= reflection.join_scopes(klass.arel_table, klass.predicate_builder, klass).inject(klass.unscoped, &:merge!)
267267
end
268268

269269
def build_scope

activerecord/test/cases/associations_test.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -428,6 +428,18 @@ def test_preload_makes_correct_number_of_queries_on_relation
428428
end
429429
end
430430

431+
def test_preload_for_hmt_with_conditions
432+
post = posts(:welcome)
433+
_normal_category = post.categories.create!(name: "Normal")
434+
special_category = post.special_categories.create!(name: "Special")
435+
436+
preloader = ActiveRecord::Associations::Preloader.new(records: [post], associations: :hmt_special_categories)
437+
preloader.call
438+
439+
assert_equal 1, post.hmt_special_categories.length
440+
assert_equal [special_category], post.hmt_special_categories
441+
end
442+
431443
def test_preload_groups_queries_with_same_scope
432444
book = books(:awdr)
433445
post = posts(:welcome)

activerecord/test/models/post.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ def greeting
114114

115115
has_many :category_posts, class_name: "CategoryPost"
116116
has_many :scategories, through: :category_posts, source: :category
117+
has_many :hmt_special_categories, -> { where.not(name: nil) }, through: :category_posts, source: :category, class_name: "SpecialCategory"
117118
has_and_belongs_to_many :categories
118119
has_and_belongs_to_many :special_categories, join_table: "categories_posts", association_foreign_key: "category_id"
119120

0 commit comments

Comments
 (0)