Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Add relation.exists?
  • Loading branch information
lifo committed Dec 27, 2009
1 parent b312334 commit 2c8f835
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
6 changes: 6 additions & 0 deletions activerecord/CHANGELOG
@@ -1,5 +1,11 @@
*Edge* *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] * Add find(ids) to relations. [Pratik Naik]


old_users = User.order("age DESC") old_users = User.order("age DESC")
Expand Down
6 changes: 6 additions & 0 deletions activerecord/lib/active_record/relation.rb
Expand Up @@ -139,6 +139,12 @@ def find(*ids, &block)
end end
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 def first
if loaded? if loaded?
@records.first @records.first
Expand Down
11 changes: 11 additions & 0 deletions activerecord/test/cases/relations_test.rb
Expand Up @@ -298,4 +298,15 @@ def test_find_ids
assert_raises(ActiveRecord::RecordNotFound) { authors.find(['invalid', 'oops']) } assert_raises(ActiveRecord::RecordNotFound) { authors.find(['invalid', 'oops']) }
end 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 end

0 comments on commit 2c8f835

Please sign in to comment.