Skip to content
This repository
Browse code

Fixed a bug when empty? was called on a grouped Relation that wasn't …

…loaded

[#5829 state:resolved]
  • Loading branch information...
commit 3a22e744162ce4d29f228e76d3e3ff355c93b88f 1 parent 4a26cd0
Andrew White authored March 12, 2011
5  activerecord/lib/active_record/relation.rb
@@ -87,7 +87,10 @@ def size
87 87
 
88 88
     # Returns true if there are no records.
89 89
     def empty?
90  
-      loaded? ? @records.empty? : count.zero?
  90
+      return @records.empty? if loaded?
  91
+
  92
+      c = count
  93
+      c.respond_to?(:zero?) ? c.zero? : c.empty?
91 94
     end
92 95
 
93 96
     def any?
30  activerecord/test/cases/relations_test.rb
@@ -639,6 +639,36 @@ def test_count_complex_chained_relations
639 639
     assert_equal expected, posts.count
640 640
   end
641 641
 
  642
+  def test_empty
  643
+    posts = Post.scoped
  644
+
  645
+    assert_queries(1) { assert_equal false, posts.empty? }
  646
+    assert ! posts.loaded?
  647
+
  648
+    no_posts = posts.where(:title => "")
  649
+    assert_queries(1) { assert_equal true, no_posts.empty? }
  650
+    assert ! no_posts.loaded?
  651
+
  652
+    best_posts = posts.where(:comments_count => 0)
  653
+    best_posts.to_a # force load
  654
+    assert_no_queries { assert_equal false, best_posts.empty? }
  655
+  end
  656
+
  657
+  def test_empty_complex_chained_relations
  658
+    posts = Post.select("comments_count").where("id is not null").group("author_id").where("comments_count > 0")
  659
+    assert_queries(1) { assert_equal false, posts.empty? }
  660
+    assert ! posts.loaded?
  661
+
  662
+    no_posts = posts.where(:title => "")
  663
+    assert_queries(1) { assert_equal true, no_posts.empty? }
  664
+    assert ! no_posts.loaded?
  665
+
  666
+    best_posts = posts.where(:comments_count => 0)
  667
+    best_posts.to_a # force load
  668
+    assert_no_queries { assert_equal true, best_posts.empty? }
  669
+    assert best_posts.loaded?
  670
+  end
  671
+
642 672
   def test_any
643 673
     posts = Post.scoped
644 674
 

0 notes on commit 3a22e74

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