Module: ActiveRecord::Associations::Preloader::ThroughAssociation

Included in:
HasManyThrough, HasOneThrough
Defined in:
activerecord/lib/active_record/associations/preloader/through_association.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#associated_records_by_owner(preloader) ⇒ Object


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
59
60
# File 'activerecord/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

    center = target_records_from_association(association)
    [owner, Array(center)]
  end

  reset_association owners, through_reflection.name

  middle_records = through_records.flat_map { |(_,rec)| rec }

  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

  through_records.each_with_object({}) do |(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

        target_records_from_association(association)
      }.compact

      # Respect the order on `reflection_scope` if it exists, else use the natural order.
      if reflection_scope.values[:order].present?
        @id_map ||= id_to_index_map @preloaded_records
        rhs_records.sort_by { |rhs| @id_map[rhs] }
      else
        rhs_records
      end
    end
  end
end

#source_reflectionObject


9
10
11
# File 'activerecord/lib/active_record/associations/preloader/through_association.rb', line 9

def source_reflection
  reflection.source_reflection
end

#through_reflectionObject


5
6
7
# File 'activerecord/lib/active_record/associations/preloader/through_association.rb', line 5

def through_reflection
  reflection.through_reflection
end