Add relation.exists?

This commit is contained in:
Pratik Naik
2009-12-27 18:00:49 +05:30
parent b31233485b
commit 2c8f83556b
3 changed files with 23 additions and 0 deletions

View File

@@ -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 File

@@ -139,6 +139,12 @@ module ActiveRecord
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 File

@@ -298,4 +298,15 @@ class RelationTest < ActiveRecord::TestCase
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