Flowdock
method

execute_grouped_calculation

Importance_0
v3.0.0 - Show latest stable - 0 notes - Class: ActiveRecord::Calculations
execute_grouped_calculation(operation, column_name) private

No documentation

This method has no description. You can help the Ruby on Rails community by adding new notes.

Hide source
# File activerecord/lib/active_record/relation/calculations.rb, line 199
    def execute_grouped_calculation(operation, column_name) #:nodoc:
      group_attr      = @group_values.first
      association     = @klass.reflect_on_association(group_attr.to_sym)
      associated      = association && association.macro == :belongs_to # only count belongs_to associations
      group_field     = associated ? association.primary_key_name : group_attr
      group_alias     = column_alias_for(group_field)
      group_column    = column_for(group_field)

      group = @klass.connection.adapter_name == 'FrontBase' ? group_alias : group_field

      aggregate_alias = column_alias_for(operation, column_name)

      select_statement = if operation == 'count' && column_name == :all
        "COUNT(*) AS count_all"
      else
        Arel::Attribute.new(@klass.unscoped, column_name).send(operation).as(aggregate_alias).to_sql
      end

      select_statement <<  ", #{group_field} AS #{group_alias}"

      relation = except(:group).select(select_statement).group(group)

      calculated_data = @klass.connection.select_all(relation.to_sql)

      if association
        key_ids     = calculated_data.collect { |row| row[group_alias] }
        key_records = association.klass.base_class.find(key_ids)
        key_records = key_records.inject({}) { |hsh, r| hsh.merge(r.id => r) }
      end

      calculated_data.inject(ActiveSupport::OrderedHash.new) do |all, row|
        key   = type_cast_calculated_value(row[group_alias], group_column)
        key   = key_records[key] if associated
        value = row[aggregate_alias]
        all[key] = type_cast_calculated_value(value, column_for(column_name), operation)
        all
      end
    end
Register or log in to add new notes.