Class: ActiveRecord::Associations::Preloader::Association

Inherits:
Object
  • Object
show all
Defined in:
activerecord/lib/active_record/associations/preloader/association.rb

Overview

:nodoc:

Direct Known Subclasses

ThroughAssociation

Instance Method Summary collapse

Constructor Details

#initialize(klass, owners, reflection, preload_scope) ⇒ Association

Returns a new instance of Association.



7
8
9
10
11
12
13
# File 'activerecord/lib/active_record/associations/preloader/association.rb', line 7

def initialize(klass, owners, reflection, preload_scope)
  @klass         = klass
  @owners        = owners
  @reflection    = reflection
  @preload_scope = preload_scope
  @model         = owners.first && owners.first.class
end

Instance Method Details

#preloaded_recordsObject



39
40
41
42
# File 'activerecord/lib/active_record/associations/preloader/association.rb', line 39

def preloaded_records
  return @preloaded_records if defined?(@preloaded_records)
  @preloaded_records = owner_keys.empty? ? [] : records_for(owner_keys)
end

#records_by_ownerObject



29
30
31
32
33
34
35
36
37
# File 'activerecord/lib/active_record/associations/preloader/association.rb', line 29

def records_by_owner
  # owners can be duplicated when a relation has a collection association join
  # #compare_by_identity makes such owners different hash keys
  @records_by_owner ||= preloaded_records.each_with_object({}.compare_by_identity) do |record, result|
    owners_by_key[convert_key(record[association_key_name])].each do |owner|
      (result[owner] ||= []) << record
    end
  end
end

#runObject



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'activerecord/lib/active_record/associations/preloader/association.rb', line 15

def run
  if !preload_scope || preload_scope.empty_scope?
    owners.each do |owner|
      associate_records_to_owner(owner, records_by_owner[owner] || [])
    end
  else
    # Custom preload scope is used and
    # the association can not be marked as loaded
    # Loading into a Hash instead
    records_by_owner
  end
  self
end