aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord
diff options
context:
space:
mode:
Diffstat (limited to 'activerecord')
-rw-r--r--activerecord/CHANGELOG2
-rwxr-xr-xactiverecord/lib/active_record/base.rb7
-rwxr-xr-xactiverecord/test/finder_test.rb7
3 files changed, 16 insertions, 0 deletions
diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG
index 8655d2bf6b..4f8204821c 100644
--- a/activerecord/CHANGELOG
+++ b/activerecord/CHANGELOG
@@ -1,5 +1,7 @@
*SVN*
+* Added Base.exists?(id) that'll return true if an object of the class with the given id exists #854 [stian@grytoyr.net]
+
* Added optionally allow for nil or empty strings with validates_numericality_of #801 [Sebastian Kanthak]
* Fixed problem with using slashes in validates_format_of regular expressions #801 [Sebastian Kanthak]
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index 7fbef9f07c..f85cad1f98 100755
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -326,6 +326,13 @@ module ActiveRecord #:nodoc:
end
end
+ # Returns true if the given +id+ represents the primary key of a record in the database, false otherwise.
+ # Example:
+ # Person.exists?(5)
+ def exists?(id)
+ !find_first("#{primary_key} = #{sanitize(id)}").nil?
+ end
+
# This method is deprecated in favor of find with the :conditions option.
# Works like find, but the record matching +id+ must also meet the +conditions+.
# +RecordNotFound+ is raised if no record can be found matching the +id+ or meeting the condition.
diff --git a/activerecord/test/finder_test.rb b/activerecord/test/finder_test.rb
index a5eaca039e..3b239b581c 100755
--- a/activerecord/test/finder_test.rb
+++ b/activerecord/test/finder_test.rb
@@ -10,6 +10,13 @@ class FinderTest < Test::Unit::TestCase
assert_equal(@topics["first"]["title"], Topic.find(1).title)
end
+ def test_exists
+ assert (Topic.exists?(1))
+ assert !(Topic.exists?(45))
+ assert !(Topic.exists?("foo"))
+ assert !(Topic.exists?([1,2]))
+ end
+
def test_find_by_array_of_one_id
assert_kind_of(Array, Topic.find([ 1 ]))
assert_equal(1, Topic.find([ 1 ]).length)