1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Fix preloading for hmt relations with conditions

This commit is contained in:
Alex Pauly 2021-11-08 17:07:17 +01:00
parent fbdb22bd1d
commit 017f727014
4 changed files with 20 additions and 1 deletions

View file

@ -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*

View file

@ -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

View file

@ -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)

View file

@ -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"