Method: WeightedAverage::ActiveRecordRelationInstanceMethods#weighted_average

Defined in:
lib/weighted_average/active_record_relation_instance_methods.rb

#weighted_average(data_column_names, options = {}) ⇒ Float?

Get the weighted average of column(s).

In addition to the options available on WeightedAverage::ArelSelectManagerInstanceMethods#weighted_average, this ActiveRecord-specific method understands associations.

Examples:

Get the average m3 of all aircraft, weighted by a column named :weighting in flight segments table. But wait… there is no column called :weighting! So see the next example.

Aircraft.weighted_average(:m3, :weighted_by => :segments)

Get the average m3 of all aircraft, weighted by how many :passengers flew in a particular aircraft.

Aircraft.weighted_average(:m3, :weighted_by => [:segments, :passengers])

Parameters:

  • data_column_names (Symbol, Array<Symbol>)

    One or more column names whose average should be calculated. Added together before being multiplied by the weighting if more than one.

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :weighted_by (Symbol)

    The name of an association to weight against OR a column name just like in the pure ARel version.

  • :weighted_by (Array{Symbol,Symbol})

    The name of an association and a weighting column inside that association table to weight against. Not available in the pure ARel version.

  • :disaggregate_by (Symbol)

    Same as its meaning in the pure ARel version.

Returns:

  • (Float, nil)

See Also:



23
24
25
26
# File 'lib/weighted_average/active_record_relation_instance_methods.rb', line 23

def weighted_average(data_column_names, options = {})
  weighted_average = connection.select_value weighted_average_relation(data_column_names, options).to_sql
  weighted_average.nil? ? nil : weighted_average.to_f
end