count

count(column_name = nil, options = {})
Instance Public methods

Count the records.

1
2
3
4
5
6
7
8
9
10
11
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:

1
2
Person.group(:city).count
# => { 'Rome' => 5, 'Paris' => 3 }

If count is used with select, it will count the selected columns:

1
2
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 databsae is thrown.

doc_ruby_on_rails
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.