Count all records using SQL. If the :counter_sql or
:finder_sql option is set for the association, it will be used for
the query. Otherwise, construct options and pass them with scope
to the target class’s count.
# File activerecord/lib/active_record/associations/collection_association.rb, line 179
def count(column_name = nil, count_options = {})
column_name, count_options = nil, column_name if column_name.is_a?(Hash)
if options[:counter_sql] || options[:finder_sql]
unless count_options.blank?
raise ArgumentError, "If finder_sql/counter_sql is used then options cannot be passed"
end
reflection.klass.count_by_sql(custom_counter_sql)
else
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
end