Module: JitPreloader::PreloaderAssociation

Defined in:
lib/jit_preloader/active_record/associations/preloader/association.rb

Instance Method Summary collapse

Instance Method Details

#associate_records_to_owner(owner, records) ⇒ Object

Original method: def associate_records_to_owner(owner, records)

association = owner.association(reflection.name)
association.loaded!
if reflection.collection?
  association.target.concat(records)
else
  association.target = records.first unless records.empty?
end

end



47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/jit_preloader/active_record/associations/preloader/association.rb', line 47

def associate_records_to_owner(owner, records)
  association = owner.association(reflection.name)
  association.loaded!

  if reflection.collection?
    # It is possible that some of the records are loaded already.
    # We don't want to duplicate them, but we also want to preserve
    # the original copy so that we don't blow away in-memory changes.
    new_records = association.target.any? ? records - association.target : records
    association.target.concat(new_records)
  else
    association.target ||= records.first unless records.empty?
  end
end

#build_scopeObject



63
64
65
66
67
# File 'lib/jit_preloader/active_record/associations/preloader/association.rb', line 63

def build_scope
  super.tap do |scope|
    scope.jit_preload! if owners.any?(&:jit_preloader) || JitPreloader.globally_enabled?
  end
end

#run(preloader) ⇒ Object

owners.each do |owner|

  associate_records_to_owner(owner, records[convert_key(owner[owner_key_name])] || [])
end

end



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/jit_preloader/active_record/associations/preloader/association.rb', line 20

def run(preloader)
  all_records = []
  records = load_records do |record|
    owner = owners_by_key[convert_key(record[association_key_name])]
    association = owner.association(reflection.name)
    association.set_inverse_instance(record)
  end

  owners.each do |owner|
    owned_records = records[convert_key(owner[owner_key_name])] || []
    all_records.concat(Array(owned_records)) if owner.jit_preloader || JitPreloader.globally_enabled?
    associate_records_to_owner(owner, owned_records)
  end

  JitPreloader::Preloader.attach(all_records) if all_records.any?
end