aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord
diff options
context:
space:
mode:
authorPratik Naik <pratiknaik@gmail.com>2009-12-29 12:15:28 +0530
committerPratik Naik <pratiknaik@gmail.com>2009-12-29 12:15:28 +0530
commitf290e685f0497427b348a2fae760300429d5f0cd (patch)
tree2a1b9e53fd55c5800a26367e64d333dcf16ec0ef /activerecord
parent13989ff8c690b9b9e5282bd4098666c909ea64d3 (diff)
downloadrails-f290e685f0497427b348a2fae760300429d5f0cd.tar.gz
rails-f290e685f0497427b348a2fae760300429d5f0cd.tar.bz2
rails-f290e685f0497427b348a2fae760300429d5f0cd.zip
Add Relation#size and Relation#empty?
Diffstat (limited to 'activerecord')
-rw-r--r--activerecord/lib/active_record/relation.rb8
-rw-r--r--activerecord/test/cases/relations_test.rb18
2 files changed, 23 insertions, 3 deletions
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index c6c63291c9..52a8bea567 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -219,6 +219,14 @@ module ActiveRecord
end
end
+ def size
+ loaded? ? @records.length : count
+ end
+
+ def empty?
+ loaded? ? @records.empty? : count.zero?
+ end
+
def destroy_all
to_a.each {|object| object.destroy}
reset
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index 92005fc224..c3cce8c5f2 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -81,7 +81,7 @@ class RelationTest < ActiveRecord::TestCase
def test_finding_with_order
topics = Topic.order('id')
- assert_equal 4, topics.size
+ assert_equal 4, topics.to_a.size
assert_equal topics(:first).title, topics.first.title
end
@@ -95,11 +95,11 @@ class RelationTest < ActiveRecord::TestCase
def test_finding_with_order_limit_and_offset
entrants = Entrant.order("id ASC").limit(2).offset(1)
- assert_equal 2, entrants.size
+ assert_equal 2, entrants.to_a.size
assert_equal entrants(:second).name, entrants.first.name
entrants = Entrant.order("id ASC").limit(2).offset(2)
- assert_equal 1, entrants.size
+ assert_equal 1, entrants.to_a.size
assert_equal entrants(:third).name, entrants.first.name
end
@@ -408,4 +408,16 @@ class RelationTest < ActiveRecord::TestCase
assert_equal 0, posts.count(:comments_count)
assert_equal 0, posts.count('comments_count')
end
+
+ def test_size
+ posts = Post.scoped
+
+ assert_queries(1) { assert_equal 7, posts.size }
+ assert ! posts.loaded?
+
+ best_posts = posts.where(:comments_count => 0)
+ best_posts.to_a # force load
+ assert_no_queries { assert_equal 5, best_posts.size }
+ end
+
end