diff options
Diffstat (limited to 'activerecord')
-rw-r--r-- | activerecord/lib/active_record/associations/singular_association.rb | 2 | ||||
-rw-r--r-- | activerecord/lib/active_record/relation.rb | 5 | ||||
-rw-r--r-- | activerecord/test/cases/relations_test.rb | 26 | ||||
-rw-r--r-- | activerecord/test/fixtures/tasks.yml | 2 |
4 files changed, 32 insertions, 3 deletions
diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb index 0d8e45adb5..4edbe216be 100644 --- a/activerecord/lib/active_record/associations/singular_association.rb +++ b/activerecord/lib/active_record/associations/singular_association.rb @@ -37,7 +37,7 @@ module ActiveRecord # Implemented by subclasses def replace(record) - raise NotImplementedError + raise NotImplementedError, "Subclasses must implement a replace(record) method" end def set_new_record(record) 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..00b7c26080 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -673,6 +673,32 @@ 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? + end + def test_any posts = Post.scoped diff --git a/activerecord/test/fixtures/tasks.yml b/activerecord/test/fixtures/tasks.yml index 1e6a061acc..01c95b3a4c 100644 --- a/activerecord/test/fixtures/tasks.yml +++ b/activerecord/test/fixtures/tasks.yml @@ -1,4 +1,4 @@ -# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html +# Read about fixtures at http://api.rubyonrails.org/classes/Fixtures.html first_task: id: 1 starting: 2005-03-30t06:30:00.00+01:00 |