execute_grouped_calculation(operation, column_name, distinct) 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 246
    def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
      group_attr      = @group_values
      association     = @klass.reflect_on_association(group_attr.first.to_sym)
      associated      = group_attr.size == 1 && association && association.macro == :belongs_to # only count belongs_to associations
      group_fields  = Array(associated ? association.foreign_key : group_attr)
      group_aliases = group_fields.map { |field| column_alias_for(field) }
      group_columns = group_aliases.zip(group_fields).map { |aliaz,field|
        [aliaz, column_for(field)]
      }

      group = @klass.connection.adapter_name == 'FrontBase' ? group_aliases : group_fields

      if operation == 'count' && column_name == :all
        aggregate_alias = 'count_all'
      else
        aggregate_alias = column_alias_for(operation, column_name)
      end

      select_values = [
        operation_over_aggregate_column(
          aggregate_column(column_name),
          operation,
          distinct).as(aggregate_alias)
      ]
      select_values += @select_values unless @having_values.empty?

      select_values.concat group_fields.zip(group_aliases).map { |field,aliaz|
        "#{field} AS #{aliaz}"
      }

      relation = except(:group).group(group.join(','))
      relation.select_values = select_values

      calculated_data = @klass.connection.select_all(relation)

      if association
        key_ids     = calculated_data.collect { |row| row[group_aliases.first] }
        key_records = association.klass.base_class.find(key_ids)
        key_records = Hash[key_records.map { |r| [r.id, r] }]
      end

      ActiveSupport::OrderedHash[calculated_data.map do |row|
        key   = group_columns.map { |aliaz, column|
          type_cast_calculated_value(row[aliaz], column)
        }
        key   = key.first if key.size == 1
        key = key_records[key] if associated
        [key, type_cast_calculated_value(row[aggregate_alias], column_for(column_name), operation)]
      end]
    end
Register or log in to add new notes.