mirror of
https://github.com/github/rails.git
synced 2026-04-26 03:00:59 -04:00
Add relation.exists?
This commit is contained in:
@@ -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")
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user