Count all records using SQL. Construct options and pass them with scope
to the target class’s count.
# File activerecord/lib/active_record/associations/collection_association.rb, line 242
def count(column_name = nil, count_options = {})
# TODO: Remove count_options argument as soon we remove support to
# activerecord-deprecated_finders.
column_name, count_options = nil, column_name if column_name.is_a?(Hash)
relation = scope
if association_scope.distinct_value
# This is needed because 'SELECT count(DISTINCT *)..' is not valid SQL.
column_name ||= reflection.klass.primary_key
relation = relation.distinct
end
value = relation.count(column_name)
limit = options[:limit]
offset = options[:offset]
if limit || offset
[ [value - offset.to_i, 0].max, limit.to_i ].min
else
value
end
end