From d1f7590577c61e33bcfa1b146971c47924823238 Mon Sep 17 00:00:00 2001 From: beerlington Date: Sun, 5 Aug 2012 10:22:05 -0400 Subject: Changing AR:CollectionAssociation#empty? to use #exists? COUNT(*) queries can be slow in PostgreSQL, #exists? avoids this by selecting a single record. --- .../active_record/associations/collection_association.rb | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) (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 f8c1103ea9..a84eda1d3b 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -270,12 +270,20 @@ module ActiveRecord load_target.size end - # Returns true if the collection is empty. Equivalent to - # collection.size.zero?. If the collection has not been already + # Returns true if the collection is empty. + # + # If the collection has been loaded or the :counter_sql option + # is provided, it is equivalent to collection.size.zero?. If the + # collection has not been loaded, it is equivalent to + # collection.exists?. If the collection has not already been # loaded and you are going to fetch the records anyway it is better to # check collection.length.zero?. def empty? - size.zero? + if loaded? || options[:counter_sql] + size.zero? + else + !scope.exists? + end end # Returns true if the collections is not empty. -- cgit v1.2.3