Joined March 2012
·

Miguel Madero

Readify
·
Sydney
·
·

Posted to ActiveRecord empty? vs count over 1 year ago

Ooops, I just read your last comment and I noticed you found that answer.

Posted to ActiveRecord empty? vs count over 1 year ago

Mario, answering one of your questions, And my surprise was that both queries use COUNT(*), empty? will only do that if you haven't loaded the results.

This is the implementation:

def empty?
  return @records.empty? if loaded?

  c = count
  c.respond_to?(:zero?) ? c.zero? : c.empty?
end

This is good to know, because you could preload them if you know you would use them, then empty? would be faster because it won't result in a DB query. Something else that's important to consider is caching this if you plan to use it more than once per request to minimize the DB calls.

Achievements
58 Karma
0 Total ProTip Views