Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

The exists? class method should treat a string argument as an id rath…

…er than as conditions. Closes #5698.

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4655 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
commit 58ebf302b206ed30568da60d7f3b124b26e9325b 1 parent 149d181
@jeremy jeremy authored
View
2  activerecord/CHANGELOG
@@ -1,5 +1,7 @@
*SVN*
+* The exists? class method should treat a string argument as an id rather than as conditions. #5698 [jeremy@planetargon.com]
+
* Fixed to_xml with :include misbehaviors when invoked on array of model instances #5690 [alexkwolfe@gmail.com]
* Added support for conditions on Base.exists? #5689 [josh@joshpeek.com]. Examples:
View
18 activerecord/lib/active_record/base.rb
@@ -426,10 +426,13 @@ def find_by_sql(sql)
# You can also pass a set of SQL conditions.
# Example:
# Person.exists?(5)
+ # Person.exists?('5')
# Person.exists?(:name => "David")
- def exists?(conditions)
- conditions = ["#{primary_key} = ?", conditions] if conditions.is_a?(Fixnum)
- !find(:first, :conditions => conditions).nil? rescue false
+ # Person.exists?(['name LIKE ?', "%#{query}%"])
+ def exists?(id_or_conditions)
+ !find(:first, :conditions => expand_id_conditions(id_or_conditions)).nil?
+ rescue ActiveRecord::ActiveRecordError
+ false
end
# Creates an object, instantly saves it as a record (if the validation permits it), and returns it. If the save
@@ -1224,6 +1227,15 @@ def attribute_condition(argument)
end
end
+ # Interpret Array and Hash as conditions and anything else as an id.
+ def expand_id_conditions(id_or_conditions)
+ case id_or_conditions
+ when Array, Hash then id_or_conditions
+ else construct_conditions_from_arguments([primary_key], [id_or_conditions])
+ end
+ end
+
+
# Defines an "attribute" method (like #inheritance_column or
# #table_name). A new (class) method will be created with the
# given name. If a value is specified, the new method will
View
15 activerecord/test/finder_test.rb
@@ -20,13 +20,14 @@ def test_find_with_string
end
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]))
+ assert Topic.exists?(1)
+ 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_raise(NoMethodError) { Topic.exists?([1,2]) }
end
def test_find_by_array_of_one_id
Please sign in to comment.
Something went wrong with that request. Please try again.