Skip to content
This repository
Browse code

fix exists? to return false if passed nil (which may come from a miss…

…ing URL param)
  • Loading branch information...
commit d48dd18bb2a3d0c46708a9ee217909783b997cb2 1 parent bb4f687
Andrew Kaspick authored August 10, 2011
4  activerecord/lib/active_record/relation/finder_methods.rb
@@ -180,7 +180,9 @@ def all(*args)
180 180
     #   Person.exists?(:name => "David")
181 181
     #   Person.exists?(['name LIKE ?', "%#{query}%"])
182 182
     #   Person.exists?
183  
-    def exists?(id = nil)
  183
+    def exists?(id = false)
  184
+      return false if id.nil?
  185
+
184 186
       id = id.id if ActiveRecord::Base === id
185 187
 
186 188
       join_dependency = construct_join_dependency_for_association_find
9  activerecord/test/cases/finder_test.rb
@@ -48,6 +48,15 @@ def test_exists_returns_true_with_one_record_and_no_args
48 48
     assert Topic.exists?
49 49
   end
50 50
 
  51
+  # exists? should handle nil for id's that come from URLs and always return false
  52
+  # (example: Topic.exists?(params[:id])) where params[:id] is nil
  53
+  def test_exists_with_nil_arg
  54
+    assert !Topic.exists?(nil)
  55
+    assert Topic.exists?
  56
+    assert !Topic.first.replies.exists?(nil)
  57
+    assert Topic.first.replies.exists?
  58
+  end
  59
+
51 60
   def test_does_not_exist_with_empty_table_and_no_args_given
52 61
     Topic.delete_all
53 62
     assert !Topic.exists?

0 notes on commit d48dd18

Please sign in to comment.
Something went wrong with that request. Please try again.