aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorChris Oliver <excid3@gmail.com>2011-03-11 16:13:44 -0600
committerAndrew White <andyw@pixeltrix.co.uk>2011-03-12 22:31:21 +0000
commit015192560b7e81639430d7e46c410bf6a3cd9223 (patch)
treebfae92c6e5577df2a82d59c81f35cd52ed6aaf15
parent1a3fe8ce42e202630e6b1d8cf7137002e270ebdb (diff)
downloadrails-015192560b7e81639430d7e46c410bf6a3cd9223.tar.gz
rails-015192560b7e81639430d7e46c410bf6a3cd9223.tar.bz2
rails-015192560b7e81639430d7e46c410bf6a3cd9223.zip
Fixed a bug when empty? was called on a grouped Relation that wasn't loaded
[#5829 state:resolved] Signed-off-by: Andrew White <andyw@pixeltrix.co.uk>
-rw-r--r--activerecord/lib/active_record/relation.rb5
-rw-r--r--activerecord/test/cases/relations_test.rb30
2 files changed, 34 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index 5af20bf38b..371403f510 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -110,7 +110,10 @@ module ActiveRecord
# Returns true if there are no records.
def empty?
- loaded? ? @records.empty? : count.zero?
+ return @records.empty? if loaded?
+
+ c = count
+ c.respond_to?(:zero?) ? c.zero? : c.empty?
end
def any?
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index 948fcf7012..ec53218451 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -673,6 +673,36 @@ class RelationTest < ActiveRecord::TestCase
assert_equal expected, posts.count
end
+ def test_empty
+ posts = Post.scoped
+
+ assert_queries(1) { assert_equal false, posts.empty? }
+ assert ! posts.loaded?
+
+ no_posts = posts.where(:title => "")
+ assert_queries(1) { assert_equal true, no_posts.empty? }
+ assert ! no_posts.loaded?
+
+ best_posts = posts.where(:comments_count => 0)
+ best_posts.to_a # force load
+ assert_no_queries { assert_equal false, best_posts.empty? }
+ end
+
+ def test_empty_complex_chained_relations
+ posts = Post.select("comments_count").where("id is not null").group("author_id").where("comments_count > 0")
+ assert_queries(1) { assert_equal false, posts.empty? }
+ assert ! posts.loaded?
+
+ no_posts = posts.where(:title => "")
+ assert_queries(1) { assert_equal true, no_posts.empty? }
+ assert ! no_posts.loaded?
+
+ best_posts = posts.where(:comments_count => 0)
+ best_posts.to_a # force load
+ assert_no_queries { assert_equal true, best_posts.empty? }
+ assert best_posts.loaded?
+ end
+
def test_any
posts = Post.scoped