From aa202adf6c78468c8e03efd11d84b71478de7b03 Mon Sep 17 00:00:00 2001 From: Francesco Rodriguez Date: Wed, 3 Oct 2012 18:02:14 -0500 Subject: Count returns 0 without querying if parent is not saved Patches `CollectionAssociation#count` to return 0 without querying if the parent record is new. Consider the following code: class Account has_many :dossiers end class Dossier belongs_to :account end a = Account.new a.dossiers.build # before patch a.dossiers.count # SELECT COUNT(*) FROM "dossiers" WHERE "dossiers"."account_id" IS NULL # => 0 # after a.dosiers.count # fires without sql query # => 0 Fixes #1856. --- activerecord/lib/active_record/associations/collection_association.rb | 2 ++ 1 file changed, 2 insertions(+) (limited to 'activerecord/lib/active_record/associations/collection_association.rb') diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index fe3e5b00f7..96270ec0e9 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -174,6 +174,8 @@ module ActiveRecord # association, it will be used for the query. Otherwise, construct options and pass them with # scope to the target class's +count+. def count(column_name = nil, count_options = {}) + return 0 if owner.new_record? + column_name, count_options = nil, column_name if column_name.is_a?(Hash) if options[:counter_sql] || options[:finder_sql] -- cgit v1.2.3