From 572dcdd7e858f126848bdf4f2be0f5cb0de7c026 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Tue, 26 Feb 2019 18:07:13 -0500 Subject: 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. --- .../lib/active_record/associations/preloader/through_association.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'activerecord/lib/active_record/associations') diff --git a/activerecord/lib/active_record/associations/preloader/through_association.rb b/activerecord/lib/active_record/associations/preloader/through_association.rb index 25254e652a..32653956b2 100644 --- a/activerecord/lib/active_record/associations/preloader/through_association.rb +++ b/activerecord/lib/active_record/associations/preloader/through_association.rb @@ -14,6 +14,7 @@ module ActiveRecord 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 @@ module ActiveRecord 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 -- cgit v1.2.3