Permalink
Browse files

Add Relation#size and Relation#empty?

  • Loading branch information...
1 parent 13989ff commit f290e685f0497427b348a2fae760300429d5f0cd @lifo lifo committed Dec 29, 2009
Showing with 23 additions and 3 deletions.
  1. +8 −0 activerecord/lib/active_record/relation.rb
  2. +15 −3 activerecord/test/cases/relations_test.rb
@@ -219,6 +219,14 @@ def last
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
@@ -81,7 +81,7 @@ def test_finding_with_conditions
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 @@ def test_finding_with_order_and_take
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 @@ def test_count_explicit_columns
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

0 comments on commit f290e68

Please sign in to comment.