diff options
author | Pratik Naik <pratiknaik@gmail.com> | 2009-12-30 12:00:26 +0530 |
---|---|---|
committer | Pratik Naik <pratiknaik@gmail.com> | 2009-12-30 12:11:22 +0530 |
commit | bdf59a561877ab9ac97a89697eaeb8e0db88a408 (patch) | |
tree | f1029320196e9ee9fbf231f03219b5a6caea6a42 | |
parent | a56518aee2258472f5f80807d733ccfa63eedb2d (diff) | |
download | rails-bdf59a561877ab9ac97a89697eaeb8e0db88a408.tar.gz rails-bdf59a561877ab9ac97a89697eaeb8e0db88a408.tar.bz2 rails-bdf59a561877ab9ac97a89697eaeb8e0db88a408.zip |
Add Relation#any? and Relation#many?
-rw-r--r-- | activerecord/lib/active_record/relation.rb | 16 | ||||
-rw-r--r-- | activerecord/test/cases/relations_test.rb | 26 |
2 files changed, 42 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 64261db809..fa517aba38 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -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 diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 7b5ff246c0..5d6f9ad430 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -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 |