Class: ActiveRecord::Associations::Preloader::SpatialAssociation

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

Overview

:nodoc:

Constant Summary collapse

SPATIAL_FIELD_ALIAS =
'__spatial_ids__'
SPATIAL_JOIN_NAME =
'__spatial_ids_join__'
SPATIAL_JOIN_QUOTED_NAME =
%{"#{SPATIAL_JOIN_NAME}"}

Instance Method Summary collapse

Instance Method Details

#records_for(ids) ⇒ Object



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
# File 'lib/activerecord-spatial/associations/active_record_3.rb', line 12

def records_for(ids)
  table_name = reflection.quoted_table_name
  join_name = model.quoted_table_name
  column = %{#{SPATIAL_JOIN_QUOTED_NAME}.#{model.quoted_primary_key}}
  geom = {
    :class => model,
    :table_alias => SPATIAL_JOIN_NAME
  }

  if reflection.options[:geom].is_a?(Hash)
    geom.merge!(reflection.options[:geom])
  else
    geom[:column] = reflection.options[:geom]
  end

  scoped.
    select(%{array_to_string(array_agg(#{column}), ',') AS "#{SPATIAL_FIELD_ALIAS}"}).
    joins(
      "INNER JOIN #{join_name} AS #{SPATIAL_JOIN_QUOTED_NAME} ON (" <<
        klass.send("st_#{reflection.options[:relationship]}",
          geom,
          (reflection.options[:scope_options] || {}).merge(
            :column => reflection.options[:foreign_geom]
          )
        ).where_values.join(' AND ') <<
      ")"
    ).
    where(model.arel_table.alias(SPATIAL_JOIN_NAME)[model.primary_key].in(ids)).
    group(table[klass.primary_key])
end