Permalink
Browse files

Add relation.exists?

  • Loading branch information...
1 parent b312334 commit 2c8f83556bf3ec9861315e11bc070753ef6bd97c @lifo lifo committed Dec 27, 2009
Showing with 23 additions and 0 deletions.
  1. +6 −0 activerecord/CHANGELOG
  2. +6 −0 activerecord/lib/active_record/relation.rb
  3. +11 −0 activerecord/test/cases/relations_test.rb
View
6 activerecord/CHANGELOG
@@ -1,5 +1,11 @@
*Edge*
+* Add relation.exists? [Pratik Naik]
+
+ red_items = Item.where(:colours => 'red')
+ red_items.exists?
+ red_items.exists?(1)
+
* Add find(ids) to relations. [Pratik Naik]
old_users = User.order("age DESC")
View
6 activerecord/lib/active_record/relation.rb
@@ -139,6 +139,12 @@ def find(*ids, &block)
end
end
+ def exists?(id = nil)
+ relation = select("#{@klass.quoted_table_name}.#{@klass.primary_key}").limit(1)
+ relation = relation.where(@klass.primary_key => id) if id
+ relation.first ? true : false
+ end
+
def first
if loaded?
@records.first
View
11 activerecord/test/cases/relations_test.rb
@@ -298,4 +298,15 @@ def test_find_ids
assert_raises(ActiveRecord::RecordNotFound) { authors.find(['invalid', 'oops']) }
end
+ def test_exists
+ davids = Author.where(:name => 'David')
+ assert davids.exists?
+ assert davids.exists?(authors(:david).id)
+ assert ! davids.exists?(authors(:mary).id)
+ assert ! davids.exists?("hax'id")
+
+ fake = Author.where(:name => 'fake author')
+ assert ! fake.exists?
+ assert ! fake.exists?(authors(:david).id)
+ end
end

0 comments on commit 2c8f835

Please sign in to comment.