Skip to content
Browse files

Changing AR:CollectionAssociation#empty? to use #exists?

COUNT(*) queries can be slow in PostgreSQL, #exists? avoids this by
selecting a single record.
  • Loading branch information...
1 parent daf9f9f commit d1f7590577c61e33bcfa1b146971c47924823238 @beerlington beerlington committed Aug 5, 2012
Showing with 11 additions and 3 deletions.
  1. +11 −3 activerecord/lib/active_record/associations/collection_association.rb
View
14 activerecord/lib/active_record/associations/collection_association.rb
@@ -270,12 +270,20 @@ def length
load_target.size
end
- # Returns true if the collection is empty. Equivalent to
- # <tt>collection.size.zero?</tt>. If the collection has not been already
+ # Returns true if the collection is empty.
+ #
+ # If the collection has been loaded or the <tt>:counter_sql</tt> option
+ # is provided, it is equivalent to <tt>collection.size.zero?</tt>. If the
+ # collection has not been loaded, it is equivalent to
+ # <tt>collection.exists?</tt>. If the collection has not already been
# loaded and you are going to fetch the records anyway it is better to
# check <tt>collection.length.zero?</tt>.
def empty?
- size.zero?
+ if loaded? || options[:counter_sql]
+ size.zero?
+ else
+ !scope.exists?
+ end
end
# Returns true if the collections is not empty.

0 comments on commit d1f7590

Please sign in to comment.
Something went wrong with that request. Please try again.