4 def add_constraints(scope)
5 tables = construct_tables
7 chain.each_with_index do |reflection, i|
8 table, foreign_table = tables.shift, tables.first
10 if reflection.source_macro == :has_and_belongs_to_many
11 join_table = tables.shift
14 # scope = scope.joins(join(
16 # table[reflection.active_record_primary_key].
17 # eq(join_table[reflection.association_foreign_key])
19 predicate = cpk_join_predicate(table, reflection.association_primary_key,
20 join_table, reflection.association_foreign_key)
21 scope = scope.joins(join(join_table, predicate))
23 table, foreign_table = join_table, tables.first
26 if reflection.source_macro == :belongs_to
27 if reflection.options[:polymorphic]
28 key = reflection.association_primary_key(klass)
30 key = reflection.association_primary_key
33 foreign_key = reflection.foreign_key
35 key = reflection.foreign_key
36 foreign_key = reflection.active_record_primary_key
39 conditions = self.conditions[i]
41 if reflection == chain.last
43 # scope = scope.where(table[key].eq(owner[foreign_key]))
44 predicate = cpk_join_predicate(table, key, owner, foreign_key)
45 scope = scope.where(predicate)
48 scope = scope.where(table[reflection.type].eq(owner.class.base_class.name))
51 conditions.each do |condition|
52 if options[:through] && condition.is_a?(Hash)
53 condition = { table.name => condition }
56 scope = scope.where(interpolate(condition))
60 # constraint = table[key].eq(foreign_table[foreign_key])
61 constraint = cpk_join_predicate(table, key, foreign_table, foreign_key)
64 type = chain[i + 1].klass.base_class.name
65 constraint = constraint.and(table[reflection.type].eq(type))
68 scope = scope.joins(join(foreign_table, constraint))
70 unless conditions.empty?
71 scope = scope.where(sanitize(conditions, table))