Module: SpatialStats::Queries::Variables

Defined in:
lib/spatial_stats/queries/variables.rb

Overview

Variables includes a method to query a field from a given scope and keep it in a consistent order with how weights are queried.

Class Method Summary collapse

Class Method Details

.query_field(scope, field) ⇒ Array

Query the given field for a scope and order by primary key

Examples:

scope = County.all
field = :avg_income
SpatialStats::Queries::Variables.query_field(scope, field)
# => [30023, 23400, 57800, ...]

Parameters:

  • scope (ActiveRecord::Relation)

    you want to query

  • field (Symbol, String)

    you want to query from the scope

Returns:

  • (Array)


22
23
24
25
26
27
28
29
30
31
32
# File 'lib/spatial_stats/queries/variables.rb', line 22

def self.query_field(scope, field)
  klass = scope.klass
  column = ActiveRecord::Base.connection.quote_column_name(field)
  primary_key = klass.quoted_primary_key
  variables = klass.find_by_sql([<<-SQL, scope: scope])
    WITH scope as (:scope)
    SELECT scope.#{column} as field FROM scope
    ORDER BY scope.#{primary_key} ASC
  SQL
  variables.map(&:field)
end