Skip to content

Commit d5b64c1

Browse files
johnnyshieldsp
andauthored
MONGOID-5029 #empty method should use an #exists? rather than a #count query (#5029)
* Fixes MONGOID-5029 - `#empty?` method should use an exists rather than a count query. - `#empty?` and `#any?` should short-circuit avoid making a query if _added is set - Make `#empty?` congruent with `#any?` code-wide * #any? is exactly the inverse of #empty? * Specs for empty? * Add spec for any * Fix all feedback from oleg * adjust the tests since there are now fewer queries Co-authored-by: shields <[email protected]> Co-authored-by: Oleg Pudeyev <[email protected]>
1 parent e98024c commit d5b64c1

File tree

3 files changed

+253
-105
lines changed

3 files changed

+253
-105
lines changed

lib/mongoid/association/referenced/has_many/enumerable.rb

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -190,9 +190,9 @@ def each
190190
# @return [ true, false ] If the enumerable is empty.
191191
def empty?
192192
if _loaded?
193-
in_memory.count == 0
193+
in_memory.empty?
194194
else
195-
_unloaded.count + _added.count == 0
195+
_added.empty? && !_unloaded.exists?
196196
end
197197
end
198198

@@ -223,11 +223,7 @@ def empty?
223223
def any?(*args)
224224
return super if args.any? || block_given?
225225

226-
if _loaded?
227-
in_memory.length > 0
228-
else
229-
_unloaded.exists? || _added.length > 0
230-
end
226+
!empty?
231227
end
232228

233229
# Get the first document in the enumerable. Will check the persisted

0 commit comments

Comments
 (0)