instance method count

Ruby on Rails 8.1.2

Since v3.0.20

Available in: v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

count(column_name = nil)

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 Relation#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 Relation#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", "technology"]=>2}

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

Person.select(:age).count
# => counts the number of different age values

Note: not all valid Relation#select expressions are valid count expressions. The specifics differ between databases. In invalid cases, an error from the database is thrown.

When given a block, calls the block with each record in the relation and returns the number of records for which the block returns a truthy value.

Person.count { |person| person.age > 21 }
# => counts the number of people older that 21

If the relation hasn’t been loaded yet, calling count with a block will load all records in the relation. If there are a lot of records in the relation, loading all records could result in performance issues.

Parameters

column_name opt = nil
Source
# File activerecord/lib/active_record/relation/calculations.rb, line 94
    def count(column_name = nil)
      if block_given?
        unless column_name.nil?
          raise ArgumentError, "Column name argument is not supported when a block is passed."
        end

        super()
      else
        calculate(:count, column_name)
      end
    end

Defined in activerecord/lib/active_record/relation/calculations.rb line 94 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::Calculations

Type at least 2 characters to search.

↑↓ navigate · open · esc close