Module: CompositePrimaryKeys::CollectionAssociation

Defined in:
lib/composite_primary_keys/associations/collection_association.rb

Instance Method Summary collapse

Instance Method Details

#get_recordsObject



3
4
5
6
7
# File 'lib/composite_primary_keys/associations/collection_association.rb', line 3

def get_records
  cpk_applies = target.try(:composite?) || owner.try(:composite?)
  return scope.to_a if cpk_applies
  super
end

#ids_readerObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/composite_primary_keys/associations/collection_association.rb', line 9

def ids_reader
  if loaded?
    load_target.map do |record|
      if reflection.association_primary_key.is_a?(Array)
        reflection.association_primary_key.map { |key| record.send(key) }
      else
        record.send(reflection.association_primary_key)
      end
    end
  else
    @association_ids ||= (
    column = "#{reflection.quoted_table_name}.#{reflection.association_primary_key}"
    scope.pluck(column)
    )
  end
end

#ids_writer(ids) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/composite_primary_keys/associations/collection_association.rb', line 26

def ids_writer(ids)
  pk_type = reflection.primary_key_type
  ids = Array(ids).reject(&:blank?)
  ids.map! { |i| pk_type.cast(i) }
  # CPK
  if reflection.association_primary_key.is_a?(Array)
    predicate = Class.new.extend(CompositePrimaryKeys::Predicates).cpk_in_predicate(klass.arel_table, reflection.association_primary_key, ids)
    records = klass.where(predicate).index_by do |r|
      reflection.association_primary_key.map{ |k| r.send(k) }
    end.values_at(*ids)
  else
    records = klass.where(reflection.association_primary_key => ids).index_by do |r|
      r.send(reflection.association_primary_key)
    end.values_at(*ids)
  end
  replace(records)
end