Add Relation#any? and Relation#many?

This commit is contained in:
Pratik Naik
2009-12-30 12:00:26 +05:30
parent a56518aee2
commit bdf59a5618
2 changed files with 42 additions and 0 deletions

View File

@@ -238,6 +238,22 @@ module ActiveRecord
loaded? ? @records.empty? : count.zero?
end
def any?
if block_given?
to_a.any? { |*block_args| yield(*block_args) }
else
!empty?
end
end
def many?
if block_given?
to_a.many? { |*block_args| yield(*block_args) }
else
size > 1
end
end
def destroy_all
to_a.each {|object| object.destroy}
reset

View File

@@ -445,4 +445,30 @@ class RelationTest < ActiveRecord::TestCase
assert_equal expected, posts.count
end
def test_any
posts = Post.scoped
assert_queries(3) do
assert posts.any? # Uses COUNT()
assert ! posts.where(:id => nil).any?
assert posts.any? {|p| p.id > 0 }
assert ! posts.any? {|p| p.id <= 0 }
end
assert posts.loaded?
end
def test_many
posts = Post.scoped
assert_queries(2) do
assert posts.many? # Uses COUNT()
assert posts.many? {|p| p.id > 0 }
assert ! posts.many? {|p| p.id < 2 }
end
assert posts.loaded?
end
end