13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
# File 'lib/active_record/associations/preloader/through_association.rb', line 13
def associated_records_by_owner(preloader)
preloader.preload(owners,
through_reflection.name,
through_scope)
through_records = owners.map do |owner|
association = owner.association through_reflection.name
[owner, Array(association.reader)]
end
reset_association owners, through_reflection.name
middle_records = through_records.map { |(_,rec)| rec }.flatten
preloaders = preloader.preload(middle_records,
source_reflection.name,
reflection_scope)
@preloaded_records = preloaders.flat_map(&:preloaded_records)
middle_to_pl = preloaders.each_with_object({}) do |pl,h|
pl.owners.each { |middle|
h[middle] = pl
}
end
record_offset = {}
@preloaded_records.each_with_index do |record,i|
record_offset[record] = i
end
through_records.each_with_object({}) { |(lhs,center),records_by_owner|
pl_to_middle = center.group_by { |record| middle_to_pl[record] }
records_by_owner[lhs] = pl_to_middle.flat_map do |pl, middles|
rhs_records = middles.flat_map { |r|
association = r.association source_reflection.name
association.reader
}.compact
rhs_records.sort_by { |rhs| record_offset[rhs] }
end
}
end
|