Class: ActiveRecord::Associations::AssociationScope

Inherits:
Object
  • Object
show all
Defined in:
lib/activerecord-spatial/associations/active_record_3.rb,
lib/activerecord-spatial/associations/active_record.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#add_constraints_with_spatial(scope) ⇒ Object



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
98
99
100
101
102
103
104
# File 'lib/activerecord-spatial/associations/active_record_3.rb', line 46

def add_constraints_with_spatial(scope)
  return add_constraints_without_spatial(scope) if !self.association.is_a?(SpatialAssociation)

  tables = construct_tables

  chain.each_with_index do |reflection, i|
    table, foreign_table = tables.shift, tables.first

    conditions = self.conditions[i]
    geom_options = {
      :class => self.association.klass
    }

    if self.association.geom.is_a?(Hash)
      geom_options.merge!(
        :value => owner[self.association.geom[:name]]
      )
      geom_options.merge!(self.association.geom)
    else
      geom_options.merge!(
        :value => owner[self.association.geom],
        :name => self.association.geom
      )
    end

    if reflection == chain.last
      scope = scope.send("st_#{self.association.relationship}", geom_options, self.association.scope_options)

      if reflection.type
        scope = scope.where(table[reflection.type].eq(owner.class.base_class.name))
      end

      conditions.each do |condition|
        scope = scope.where(interpolate(condition))
      end
    else
      constraint = scope.where(
        scope.send(
          "st_#{self.association.relationship}",
          owner[self.association.foreign_geom],
          self.association.scope_options
        ).where_values
      ).join(' AND ')

      if reflection.type
        type = chain[i + 1].klass.base_class.name
        constraint = table[reflection.type].eq(type).and(constraint)
      end

      scope = scope.joins(join(foreign_table, constraint))

      unless conditions.empty?
        scope = scope.where(sanitize(conditions, table))
      end
    end
  end

  scope
end