Class: ROM::SQL::Association::ManyToOne

Inherits:
ROM::SQL::Association show all
Defined in:
lib/rom/sql/association/many_to_one.rb

Instance Attribute Summary

Attributes inherited from ROM::SQL::Association

#as, #relation, #result, #source, #target

Instance Method Summary collapse

Methods inherited from ROM::SQL::Association

#initialize, #qualify

Constructor Details

This class inherits a constructor from ROM::SQL::Association

Instance Method Details

#associate(relations, child, parent) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



43
44
45
46
# File 'lib/rom/sql/association/many_to_one.rb', line 43

def associate(relations, child, parent)
  fk, pk = join_key_map(relations)
  child.merge(fk => parent.fetch(pk))
end

#call(relations) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/rom/sql/association/many_to_one.rb', line 8

def call(relations)
  left = relations[target.relation]
  right = relations[source.relation]

  right_pk = right.schema.primary_key.map { |a| a.meta[:name] }
  right_fk = right.foreign_key(target.relation)

  pk_to_fk = Hash[right_pk.product(Array(left.foreign_key(source.relation)))]

  columns = left.header.qualified.to_a + right.header
    .project(*right_pk)
    .rename(pk_to_fk)
    .qualified.to_a

  relation = left
    .inner_join(source, right_fk => left.primary_key)
    .select(*columns)
    .order(*right.header.project(*right.primary_key).qualified)

  relation.with(attributes: relation.header.names)
end

#combine_keys(relations) ⇒ Object



31
32
33
# File 'lib/rom/sql/association/many_to_one.rb', line 31

def combine_keys(relations)
  Hash[*with_keys(relations)]
end

#join_keys(relations) ⇒ Object



36
37
38
39
40
# File 'lib/rom/sql/association/many_to_one.rb', line 36

def join_keys(relations)
  with_keys(relations) { |source_key, target_key|
    { qualify(source, source_key) => qualify(target, target_key) }
  }
end