Calculates the average value on a given column. Returns nil if there’s no row. See calculate for examples with options.
Person.average('age') # => 35.8
# File lib/active_record/relation/calculations.rb, line 65 65: def average(column_name, options = {}) 66: calculate(:average, column_name, options) 67: end
This calculates aggregate values in the given column. Methods for count, sum, average, minimum, and maximum have been added as shortcuts. Options such as :conditions, :order, :group, :having, and :joins can be passed to customize the query.
There are two basic forms of output:
* Single aggregate value: The single value is type cast to Fixnum for COUNT, Float for AVG, and the given column's type for everything else. * Grouped values: This returns an ordered hash of the values and groups them by the <tt>:group</tt> option. It takes either a column name, or the name of a belongs_to association. values = Person.maximum(:age, :group => 'last_name') puts values["Drake"] => 43 drake = Family.find_by_last_name('Drake') values = Person.maximum(:age, :group => :family) # Person belongs_to :family puts values[drake] => 43 values.each do |family, max_age| ... end
Options:
:conditions - An SQL fragment like “administrator = 1” or [ “user_name = ?”, username ]. See conditions in the intro to ActiveRecord::Base.
:include: Eager loading, see Associations for details. Since calculations don’t load anything, the purpose of this is to access fields on joined tables in your conditions, order, or group clauses.
:joins - An SQL fragment for additional joins like “LEFT JOIN comments ON comments.post_id = id”. (Rarely needed). The records will be returned read-only since they will have attributes that do not correspond to the table’s columns.
:order - An SQL fragment like “created_at DESC, name” (really only used with GROUP BY calculations).
:group - An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
:select - By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join, but not include the joined columns.
:distinct - Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) …
Examples:
Person.calculate(:count, :all) # The same as Person.count Person.average(:age) # SELECT AVG(age) FROM people... Person.minimum(:age, :conditions => ['last_name != ?', 'Drake']) # Selects the minimum age for # everyone with a last name other than 'Drake' # Selects the minimum age for any family without any minors Person.minimum(:age, :having => 'min(age) > 17', :group => :last_name) Person.sum("2 * age")
# File lib/active_record/relation/calculations.rb, line 149 149: def calculate(operation, column_name, options = {}) 150: if options.except(:distinct).present? 151: apply_finder_options(options.except(:distinct)).calculate(operation, column_name, :distinct => options[:distinct]) 152: else 153: relation = with_default_scope 154: 155: if relation.equal?(self) 156: if eager_loading? || (includes_values.present? && references_eager_loaded_tables?) 157: construct_relation_for_association_calculations.calculate(operation, column_name, options) 158: else 159: perform_calculation(operation, column_name, options) 160: end 161: else 162: relation.calculate(operation, column_name, options) 163: end 164: end 165: rescue ThrowResult 166: 0 167: end
Count operates using three different approaches.
Count all: By not passing any parameters to count, it will return a count of all the rows for the model.
Count using column: By passing a column name to count, it will return a count of all the rows for the model with supplied column present.
Count using options will find the row count matched by the options used.
The third approach, count using options, accepts an option hash as the only parameter. The options are:
:conditions: An SQL fragment like “administrator = 1” or [ “user_name = ?”, username ]. See conditions in the intro to ActiveRecord::Base.
:joins: Either an SQL fragment for additional joins like “LEFT JOIN comments ON comments.post_id = id” (rarely needed) or named associations in the same form used for the :include option, which will perform an INNER JOIN on the associated table(s). If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table’s columns. Pass :readonly => false to override.
:include: Named associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer to already defined associations. When using named associations, count returns the number of DISTINCT items for the model you’re counting. See eager loading under Associations.
:order: An SQL fragment like “created_at DESC, name” (really only used with GROUP BY calculations).
:group: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
:select: By default, this is * as in SELECT * FROM, but can be changed if you, for example, want to do a join but not include the joined columns.
:distinct: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) …
:from - By default, this is the table name of the class, but can be changed to an alternate table name (or even the name of a database view).
Examples for counting all:
Person.count # returns the total count of all people
Examples for counting by column:
Person.count(:age) # returns the total count of all people whose age is present in database
Examples for count with options:
Person.count(:conditions => "age > 26") # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN. Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job) # finds the number of rows matching the conditions and joins. Person.count(:conditions => "age > 26 AND job.salary > 60000", :joins => "LEFT JOIN jobs on jobs.person_id = person.id") Person.count('id', :conditions => "age > 26") # Performs a COUNT(id) Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*')
Note: Person.count(:all) will not work because it will use :all as the condition. Use Person.count instead.
# File lib/active_record/relation/calculations.rb, line 56 56: def count(column_name = nil, options = {}) 57: column_name, options = nil, column_name if column_name.is_a?(Hash) 58: calculate(:count, column_name, options) 59: end
Calculates the maximum value on a given column. The value is returned with the same data type of the column, or nil if there’s no row. See calculate for examples with options.
Person.maximum('age') # => 93
# File lib/active_record/relation/calculations.rb, line 83 83: def maximum(column_name, options = {}) 84: calculate(:maximum, column_name, options) 85: end
Calculates the minimum value on a given column. The value is returned with the same data type of the column, or nil if there’s no row. See calculate for examples with options.
Person.minimum('age') # => 7
# File lib/active_record/relation/calculations.rb, line 74 74: def minimum(column_name, options = {}) 75: calculate(:minimum, column_name, options) 76: end
This method is designed to perform select by a single column as direct SQL query Returns Array with values of the specified column name The values has same data type as column.
Examples:
Person.pluck(:id) # SELECT people.id FROM people Person.uniq.pluck(:role) # SELECT DISTINCT role FROM people Person.where(:confirmed => true).limit(5).pluck(:id)
# File lib/active_record/relation/calculations.rb, line 179 179: def pluck(column_name) 180: column_name = column_name.to_s 181: klass.connection.select_all(select(column_name).arel).map! do |attributes| 182: klass.type_cast_attribute(attributes.keys.first, klass.initialize_attributes(attributes)) 183: end 184: end
Calculates the sum of values on a given column. The value is returned with the same data type of the column, 0 if there’s no row. See calculate for examples with options.
Person.sum('age') # => 4562
# File lib/active_record/relation/calculations.rb, line 92 92: def sum(*args) 93: if block_given? 94: self.to_a.sum(*args) {|*block_args| yield(*block_args)} 95: else 96: calculate(:sum, *args) 97: end 98: end
# File lib/active_record/relation/calculations.rb, line 212 212: def aggregate_column(column_name) 213: if @klass.column_names.include?(column_name.to_s) 214: Arel::Attribute.new(@klass.unscoped.table, column_name) 215: else 216: Arel.sql(column_name == :all ? "*" : column_name.to_s) 217: end 218: end
# File lib/active_record/relation/calculations.rb, line 352 352: def build_count_subquery(relation, column_name, distinct) 353: column_alias = Arel.sql('count_column') 354: subquery_alias = Arel.sql('subquery_for_count') 355: 356: aliased_column = aggregate_column(column_name == :all ? 1 : column_name).as(column_alias) 357: relation.select_values = [aliased_column] 358: subquery = relation.arel.as(subquery_alias) 359: 360: sm = Arel::SelectManager.new relation.engine 361: select_value = operation_over_aggregate_column(column_alias, 'count', distinct) 362: sm.project(select_value).from(subquery) 363: end
Converts the given keys to the value that the database adapter returns as a usable column name:
column_alias_for("users.id") # => "users_id" column_alias_for("sum(id)") # => "sum_id" column_alias_for("count(distinct users.id)") # => "count_distinct_users_id" column_alias_for("count(*)") # => "count_all" column_alias_for("count", "id") # => "count_id"
# File lib/active_record/relation/calculations.rb, line 315 315: def column_alias_for(*keys) 316: keys.map! {|k| k.respond_to?(:to_sql) ? k.to_sql : k} 317: table_name = keys.join(' ') 318: table_name.downcase! 319: table_name.gsub!(/\*/, 'all') 320: table_name.gsub!(/\W+/, ' ') 321: table_name.strip! 322: table_name.gsub!(/ +/, '_') 323: 324: @klass.connection.table_alias_for(table_name) 325: end
# File lib/active_record/relation/calculations.rb, line 327 327: def column_for(field) 328: field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split('.').last 329: @klass.columns.detect { |c| c.name.to_s == field_name } 330: end
# File lib/active_record/relation/calculations.rb, line 220 220: def operation_over_aggregate_column(column, operation, distinct) 221: operation == 'count' ? column.count(distinct) : column.send(operation) 222: end
# File lib/active_record/relation/calculations.rb, line 188 188: def perform_calculation(operation, column_name, options = {}) 189: operation = operation.to_s.downcase 190: 191: distinct = options[:distinct] 192: 193: if operation == "count" 194: column_name ||= (select_for_count || :all) 195: 196: unless arel.ast.grep(Arel::Nodes::OuterJoin).empty? 197: distinct = true 198: end 199: 200: column_name = primary_key if column_name == :all && distinct 201: 202: distinct = nil if column_name =~ /\s*DISTINCT\s+/ 203: end 204: 205: if @group_values.any? 206: execute_grouped_calculation(operation, column_name, distinct) 207: else 208: execute_simple_calculation(operation, column_name, distinct) 209: end 210: end
# File lib/active_record/relation/calculations.rb, line 345 345: def select_for_count 346: if @select_values.present? 347: select = @select_values.join(", ") 348: select if select !~ /(,|\*)/ 349: end 350: end
# File lib/active_record/relation/calculations.rb, line 332 332: def type_cast_calculated_value(value, column, operation = nil) 333: case operation 334: when 'count' then value.to_i 335: when 'sum' then type_cast_using_column(value || '0', column) 336: when 'average' then value.respond_to?(:to_d) ? value.to_d : value 337: else type_cast_using_column(value, column) 338: end 339: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.