Permalink
Browse files

Added support for conditions on Base.exists? (closes #5689) [josh@jos…

…hpeek.com]

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4651 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
1 parent 29ae3e9 commit 8085cbfd0898676ffaea2f2d1c2616e47a37e5e1 @dhh dhh committed Aug 3, 2006
Showing with 14 additions and 2 deletions.
  1. +6 −0 activerecord/CHANGELOG
  2. +5 −2 activerecord/lib/active_record/base.rb
  3. +3 −0 activerecord/test/finder_test.rb
View
@@ -1,5 +1,11 @@
*SVN*
+* Added support for conditions on Base.exists? #5689 [josh@joshpeek.com]. Examples:
+
+ assert (Topic.exists?(:author_name => "David"))
+ assert (Topic.exists?(:author_name => "Mary", :approved => true))
+ assert (Topic.exists?(["parent_id = ?", 1]))
+
* Schema dumper quotes date :default values. [Dave Thomas]
* Calculate sum with SQL, not Enumerable on HasManyThrough Associations. [Dan Peterson]
@@ -423,10 +423,13 @@ def find_by_sql(sql)
end
# Returns true if the given +id+ represents the primary key of a record in the database, false otherwise.
+ # You can also pass a set of SQL conditions.
# Example:
# Person.exists?(5)
- def exists?(id)
- !find(:first, :conditions => ["#{primary_key} = ?", id]).nil? rescue false
+ # Person.exists?(:name => "David")
+ def exists?(conditions)
+ conditions = ["#{primary_key} = ?", conditions] if conditions.is_a?(Fixnum)
+ !find(:first, :conditions => conditions).nil? rescue false
end
# Creates an object, instantly saves it as a record (if the validation permits it), and returns it. If the save
@@ -21,6 +21,9 @@ def test_find_with_string
def test_exists
assert (Topic.exists?(1))
+ assert (Topic.exists?(:author_name => "David"))
+ assert (Topic.exists?(:author_name => "Mary", :approved => true))
+ assert (Topic.exists?(["parent_id = ?", 1]))
assert !(Topic.exists?(45))
assert !(Topic.exists?("foo"))
assert !(Topic.exists?([1,2]))

0 comments on commit 8085cbf

Please sign in to comment.