Fix preload with nested associations

When the middle association doesn't have any records and the inner
association is not an empty scope the owner will be `nil` so we can't
try to reset the inverse association.
This commit is contained in:
Rafael Mendonça França 2019-02-26 18:07:13 -05:00
parent 196e22de53
commit 572dcdd7e8
No known key found for this signature in database
GPG Key ID: FC23B6D0F1EEE948
3 changed files with 16 additions and 1 deletions

@ -14,6 +14,7 @@ def run(preloader)
owners.each do |owner|
through_records = Array(owner.association(through_reflection.name).target)
if already_loaded
if source_type = reflection.options[:source_type]
through_records = through_records.select do |record|
@ -23,17 +24,20 @@ def run(preloader)
else
owner.association(through_reflection.name).reset if through_scope
end
result = through_records.flat_map do |record|
record.association(source_reflection.name).target
end
result.compact!
result.sort_by! { |rhs| preload_index[rhs] } if scope.order_values.any?
result.uniq! if scope.distinct_value
associate_records_to_owner(owner, result)
end
unless scope.empty_scope?
middle_records.each do |owner|
owner.association(source_reflection.name).reset
owner.association(source_reflection.name).reset if owner
end
end
end

@ -55,6 +55,15 @@ def test_marshal_dump
assert_equal preloaded, Marshal.load(Marshal.dump(preloaded))
end
def test_preload_with_nested_association
posts = Post.preload(:author, :author_favorites).to_a
assert_no_queries do
posts.each(&:author)
posts.each(&:author_favorites)
end
end
def test_preload_sti_rhs_class
developers = Developer.includes(:firms).all.to_a
assert_no_queries do

@ -217,6 +217,8 @@ def self.destroyed_author_address_ids
end
class AuthorFavorite < ActiveRecord::Base
default_scope { order(id: :asc) }
belongs_to :author
belongs_to :favorite_author, class_name: "Author"
end