Browse files

ActiveRecord::Relation#blank? should `LIMIT 1`

This is an SQL improvement to ActiveRecord::Relation#blank?. Currently,
it calls `to_a` on the Relation, which loads all records in the
association, and calls `blank?` on the loaded Array. There are other
ways, however, to check the emptiness of an association that are far
more performant. `#empty?`, `#exists?` and `#any?` all attach a `LIMIT
1` to the SQL query before firing it off, which is a nice query
improvement. `#blank?` should do the same!

Bonus performance improvements will also happen for `#present?`, which
merely calls the negation of `#blank?`

Signed-off-by: David Celis <>
  • Loading branch information...
1 parent 94725b8 commit 4e2bec383239f9ab3493208ef3bad1f2cbea3c93 @davidcelis davidcelis committed May 9, 2013
Showing with 1 addition and 5 deletions.
  1. +1 −5 activerecord/lib/active_record/relation.rb
@@ -21,6 +21,7 @@ class Relation
alias :model :klass
alias :loaded? :loaded
alias :default_scoped? :default_scoped
+ alias :blank? :empty?
def initialize(klass, table, values = {})
@klass = klass
@@ -575,11 +576,6 @@ def with_default_scope #:nodoc:
- # Returns true if relation is blank.
- def blank?
- to_a.blank?
- end
def values

0 comments on commit 4e2bec3

Please sign in to comment.