4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
# File 'lib/composite_primary_keys/associations/association_scope.rb', line 4
def add_constraints(scope, owner, assoc_klass, refl, tracker)
chain = refl.chain
scope_chain = refl.scope_chain
tables = construct_tables(chain, assoc_klass, refl, tracker)
chain.each_with_index do |reflection, i|
table, foreign_table = tables.shift, tables.first
if reflection.source_macro == :belongs_to
if reflection.options[:polymorphic]
key = reflection.association_primary_key(assoc_klass)
else
key = reflection.association_primary_key
end
foreign_key = reflection.foreign_key
else
key = reflection.foreign_key
foreign_key = reflection.active_record_primary_key
end
if reflection == chain.last
predicate = cpk_join_predicate(table, key, owner, foreign_key)
scope = scope.where(predicate)
if reflection.type
value = owner.class.base_class.name
bind_val = bind scope, table.table_name, reflection.type.to_s, value, tracker
scope = scope.where(table[reflection.type].eq(bind_val))
end
else
constraint = cpk_join_predicate(table, key, foreign_table, foreign_key)
if reflection.type
value = chain[i + 1].klass.base_class.name
bind_val = bind scope, table.table_name, reflection.type.to_s, value, tracker
scope = scope.where(table[reflection.type].eq(bind_val))
end
scope = scope.joins(join(foreign_table, constraint))
end
is_first_chain = i == 0
klass = is_first_chain ? assoc_klass : reflection.klass
scope_chain[i].each do |scope_chain_item|
item = eval_scope(klass, scope_chain_item, owner)
if scope_chain_item == refl.scope
scope.merge! item.except(:where, :includes, :bind)
end
if is_first_chain
scope.includes! item.includes_values
end
scope.where_values += item.where_values
scope.order_values |= item.order_values
end
end
scope
end
|