instance method
count
Ruby on Rails 4.2.9
Since v3.0.20Signature
count(column_name = nil, options = {})
Count the records.
Person.count # => the total count of all people Person.count(:age) # => returns the total count of all people whose age is present in database Person.count(:all) # => performs a COUNT(*) (:all is an alias for '*') Person.distinct.count(:age) # => counts the number of different age values
If count is used with group, it returns a Hash whose keys represent the aggregated column, and the values are the respective amounts:
Person.group(:city).count # => { 'Rome' => 5, 'Paris' => 3 }
If count is used with group for multiple columns, it returns a Hash whose keys are an array containing the individual values of each column and the value of each key would be the count.
Article.group(:status, :category).count
# => {["draft", "business"]=>10, ["draft", "technology"]=>4,
["published", "business"]=>0, ["published", "technology"]=>2}
If count is used with select, it will count the selected columns:
Person.select(:age).count # => counts the number of different age values
Note: not all valid select expressions are valid count expressions. The specifics differ between databases. In invalid cases, an error from the database is thrown.
Parameters
-
column_nameopt = nil -
optionsopt = {}
Source
# File activerecord/lib/active_record/relation/calculations.rb, line 38
def count(column_name = nil, options = {})
if options.present? && !ActiveRecord.const_defined?(:DeprecatedFinders)
raise ArgumentError, "Relation#count does not support finder options anymore. " \
"Please build a scope and then call count on it or use the " \
"activerecord-deprecated_finders gem to enable this functionality."
end
# TODO: Remove options argument as soon we remove support to
# activerecord-deprecated_finders.
calculate(:count, column_name, options)
end
Defined in activerecord/lib/active_record/relation/calculations.rb line 38
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::Calculations