Module: Torque::PostgreSQL::Associations::Preloader::Association

Defined in:
lib/torque/postgresql/associations/preloader/association.rb

Instance Method Summary collapse

Instance Method Details

#load_records(raw_records = nil) ⇒ Object

Requires a slight change when running on has many since the value of the foreign key being an array



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/torque/postgresql/associations/preloader/association.rb', line 38

def load_records(raw_records = nil)
  return super unless connected_through_array? && @reflection.macro == :has_many

  @records_by_owner = {}.compare_by_identity
  raw_records ||= loader_query.records_for([self])

  @preloaded_records = raw_records.select do |record|
    assignments = false

    keys = convert_key(record[association_key_name]) || []
    owners_by_key.values_at(*keys).each do |owner|
      entries = (@records_by_owner[owner] ||= [])

      if reflection.collection? || entries.empty?
        entries << record
        assignments = true
      end
    end

    assignments
  end
end

#owners_by_keyObject

Make sure to change the process when connected through an array



62
63
64
65
66
67
68
69
# File 'lib/torque/postgresql/associations/preloader/association.rb', line 62

def owners_by_key
  return super unless connected_through_array?
  @owners_by_key ||= owners.each_with_object({}) do |owner, result|
    Array.wrap(convert_key(owner[owner_key_name])).each do |key|
      (result[key] ||= []) << owner
    end
  end
end

#runObject

For reflections connected through an array, make sure to properly decuple the list of ids and set them as associated with the owner



13
14
15
16
17
18
19
20
# File 'lib/torque/postgresql/associations/preloader/association.rb', line 13

def run
  return self if run?
  return super unless connected_through_array?

  @run = true
  send("run_array_for_#{@reflection.macro}")
  self
end

#set_inverse(record) ⇒ Object

Correctly correlate records when they are connected theough an array



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/torque/postgresql/associations/preloader/association.rb', line 23

def set_inverse(record)
  return super unless connected_through_array? && @reflection.macro == :has_many

  # Only the first owner is associated following the same instruction
  # on the original implementation
  convert_key(record[association_key_name])&.each do |key|
    if owners = owners_by_key[key]
      association = owners.first.association(reflection.name)
      association.set_inverse_instance(record)
    end
  end
end