count

Icon_private_sm= private
Icon_protected_sm= protected

count(column_name = nil) public

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 [rdoc-ref:QueryMethods#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 [rdoc-ref:QueryMethods#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> 
Person.select(:age).count # => counts the number of different age values 

Note: not all valid [rdoc-ref:QueryMethods#select] expressions are valid #count expressions. The specifics differ between databases. In invalid cases, an error from the database is thrown.

# File activerecord/lib/active_record/relation/calculations.rb, line 41 def count(column_name = nil) if block_given? unless column_name.nil? ActiveSupport::Deprecation.warn "When `count' is called with a block, it ignores other arguments. " "This behavior is now deprecated and will result in an ArgumentError in Rails 6.0." end return super() end calculate(:count, column_name) end
Register or log in to add new notes.


APIdock release: IRON STEVE (1.4)
If you have any comments, ideas or feedback, feel free to contact us at

Go to Nodeta blog

APIdock copyright Nodeta Oy 2008-2024