From 2c8f83556bf3ec9861315e11bc070753ef6bd97c Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Sun, 27 Dec 2009 18:00:49 +0530 Subject: Add relation.exists? --- activerecord/CHANGELOG | 6 ++++++ activerecord/lib/active_record/relation.rb | 6 ++++++ activerecord/test/cases/relations_test.rb | 11 +++++++++++ 3 files changed, 23 insertions(+) (limited to 'activerecord') diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG index a2c5528860..3c60bf4f21 100644 --- a/activerecord/CHANGELOG +++ b/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") diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 87f6aa3643..4ca6871d0f 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -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 diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 9c5a38a399..d65fb5095c 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -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 -- cgit v1.2.3