Count all records using SQL. If the :counter_sql option is set for
the association, it will be used for the query. If no :counter_sql
was supplied, but :finder_sql was set, the descendant’s
construct_sql method will have set :counter_sql automatically.
Otherwise, construct options and pass them with scope to the target
class’s count.
# File activerecord/lib/active_record/associations/association_collection.rb, line 185
def count(column_name = nil, options = {})
column_name, options = nil, column_name if column_name.is_a?(Hash)
if @reflection.options[:finder_sql] || @reflection.options[:counter_sql]
unless options.blank?
raise ArgumentError, "If finder_sql/counter_sql is used then options cannot be passed"
end
@reflection.klass.count_by_sql(@counter_sql)
else
if @reflection.options[:uniq]
# This is needed because 'SELECT count(DISTINCT *)..' is not valid SQL.
column_name = "#{@reflection.quoted_table_name}.#{@reflection.klass.primary_key}" unless column_name
options.merge!(:distinct => true)
end
value = @reflection.klass.send(:with_scope, construct_scope) { @reflection.klass.count(column_name, options) }
limit = @reflection.options[:limit]
offset = @reflection.options[:offset]
if limit || offset
[ [value - offset.to_i, 0].max, limit.to_i ].min
else
value
end
end
end