|
1 |
| -require 'polyamorous/activerecord_6.1_ruby_2/join_association' |
| 1 | +module Polyamorous |
| 2 | + module JoinAssociationExtensions |
| 3 | + # Same as #join_constraints, but instead of constructing tables from the |
| 4 | + # given block, uses the ones passed |
| 5 | + def join_constraints_with_tables(foreign_table, foreign_klass, join_type, alias_tracker, tables) |
| 6 | + joins = [] |
| 7 | + chain = [] |
| 8 | + |
| 9 | + reflection.chain.each.with_index do |reflection, i| |
| 10 | + table = tables[i] |
| 11 | + |
| 12 | + @table ||= table |
| 13 | + chain << [reflection, table] |
| 14 | + end |
| 15 | + |
| 16 | + base_klass.with_connection do |connection| |
| 17 | + # The chain starts with the target table, but we want to end with it here (makes |
| 18 | + # more sense in this context), so we reverse |
| 19 | + chain.reverse_each do |reflection, table| |
| 20 | + klass = reflection.klass |
| 21 | + |
| 22 | + join_scope = reflection.join_scope(table, foreign_table, foreign_klass) |
| 23 | + |
| 24 | + unless join_scope.references_values.empty? |
| 25 | + join_dependency = join_scope.construct_join_dependency( |
| 26 | + join_scope.eager_load_values | join_scope.includes_values, Arel::Nodes::OuterJoin |
| 27 | + ) |
| 28 | + join_scope.joins!(join_dependency) |
| 29 | + end |
| 30 | + |
| 31 | + arel = join_scope.arel(alias_tracker.aliases) |
| 32 | + nodes = arel.constraints.first |
| 33 | + |
| 34 | + if nodes.is_a?(Arel::Nodes::And) |
| 35 | + others = nodes.children.extract! do |node| |
| 36 | + !Arel.fetch_attribute(node) { |attr| attr.relation.name == table.name } |
| 37 | + end |
| 38 | + end |
| 39 | + |
| 40 | + joins << table.create_join(table, table.create_on(nodes), join_type) |
| 41 | + |
| 42 | + if others && !others.empty? |
| 43 | + joins.concat arel.join_sources |
| 44 | + append_constraints(connection, joins.last, others) |
| 45 | + end |
| 46 | + |
| 47 | + # The current table in this iteration becomes the foreign table in the next |
| 48 | + foreign_table, foreign_klass = table, klass |
| 49 | + end |
| 50 | + |
| 51 | + joins |
| 52 | + end |
| 53 | + end |
| 54 | + end |
| 55 | +end |
0 commit comments