Class: ActiveRecord::Associations::JoinDependency::JoinAssociation

Inherits:
JoinPart
  • Object
show all
Defined in:
lib/store_base_sti_class_for_3_1.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#join_to(relation) ⇒ Object



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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/store_base_sti_class_for_3_1.rb', line 38

def join_to(relation)

  tables        = @tables.dup
  foreign_table = parent_table
  foreign_klass = parent.active_record

  # The chain starts with the target table, but we want to end with it here (makes
  # more sense in this context), so we reverse
  chain.reverse.each_with_index do |reflection, i|
    table = tables.shift

    case reflection.source_macro
    when :belongs_to
      key         = reflection.association_primary_key
      foreign_key = reflection.foreign_key
    when :has_and_belongs_to_many
      # Join the join table first...
      relation.from(join(
        table,
        table[reflection.foreign_key].
          eq(foreign_table[reflection.active_record_primary_key])
      ))

      foreign_table, table = table, tables.shift

      key         = reflection.association_primary_key
      foreign_key = reflection.association_foreign_key
    else
      key         = reflection.foreign_key
      foreign_key = reflection.active_record_primary_key
    end

    constraint = build_constraint(reflection, table, key, foreign_table, foreign_key)

    conditions = self.conditions[i].dup
    
    # START PATCH
    # original:
    # conditions << { reflection.type => foreign_klass.base_class.name } if reflection.type
    
    if ActiveRecord::Base.store_base_sti_class
      conditions << { reflection.type => foreign_klass.base_class.name } if reflection.type
    else
      conditions << { reflection.type => ([foreign_klass] + foreign_klass.descendants).map(&:name) } if reflection.type
    end
    
    # END PATCH

    unless conditions.empty?
      constraint = constraint.and(sanitize(conditions, table))
    end

    relation.from(join(table, constraint))

    # The current table in this iteration becomes the foreign table in the next
    foreign_table, foreign_klass = table, reflection.klass
  end

  relation
end