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

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

Defined Under Namespace

Classes: LoaderQuery

Instance Method Summary collapse

Instance Method Details

#owners_by_keyObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/composite_primary_keys/associations/preloader/association.rb', line 35

def owners_by_key
  @owners_by_key ||= owners.each_with_object({}) do |owner, result|
    # CPK
    # key = convert_key(owner[owner_key_name])
    key = if owner_key_name.is_a?(Array)
            Array(owner_key_name).map do |key_name|
              convert_key(owner[key_name])
            end
          else
            convert_key(owner[owner_key_name])
          end
    (result[key] ||= []) << owner if key
  end
end

#records_for(ids) ⇒ Object

TODO: is records_for needed anymore? Rails’ implementation has changed significantly



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

def records_for(ids)
  records = if association_key_name.is_a?(Array)
              predicate = cpk_in_predicate(klass.arel_table, association_key_name, ids)
              scope.where(predicate)
            else
              scope.where(association_key_name => ids)
            end
  records.load do |record|
    # Processing only the first owner
    # because the record is modified but not an owner
    owner = owners_by_key[convert_key(record[association_key_name])].first
    association = owner.association(reflection.name)
    association.set_inverse_instance(record)
  end
end