Skip to content
This repository
Browse code

Change exists? so that it doesn't instantiate records [#6127 state:re…

…solved]
  • Loading branch information...
commit b155fdadf334cff32a7e648c86c3c97f2f51257f 1 parent 84a4ef6
Andrew White authored March 29, 2011
14  activerecord/lib/active_record/relation/finder_methods.rb
@@ -183,7 +183,9 @@ def all(*args)
183 183
     def exists?(id = nil)
184 184
       id = id.id if ActiveRecord::Base === id
185 185
 
186  
-      relation = select("1").limit(1)
  186
+      join_dependency = construct_join_dependency_for_association_find
  187
+      relation = construct_relation_for_association_find(join_dependency)
  188
+      relation = relation.except(:select).select("1").limit(1)
187 189
 
188 190
       case id
189 191
       when Array, Hash
@@ -192,14 +194,13 @@ def exists?(id = nil)
192 194
         relation = relation.where(table[primary_key].eq(id)) if id
193 195
       end
194 196
 
195  
-      relation.first ? true : false
  197
+      connection.select_value(relation.to_sql) ? true : false
196 198
     end
197 199
 
198 200
     protected
199 201
 
200 202
     def find_with_associations
201  
-      including = (@eager_load_values + @includes_values).uniq
202  
-      join_dependency = ActiveRecord::Associations::JoinDependency.new(@klass, including, [])
  203
+      join_dependency = construct_join_dependency_for_association_find
203 204
       relation = construct_relation_for_association_find(join_dependency)
204 205
       rows = connection.select_all(relation.to_sql, 'SQL', relation.bind_values)
205 206
       join_dependency.instantiate(rows)
@@ -207,6 +208,11 @@ def find_with_associations
207 208
       []
208 209
     end
209 210
 
  211
+    def construct_join_dependency_for_association_find
  212
+      including = (@eager_load_values + @includes_values).uniq
  213
+      ActiveRecord::Associations::JoinDependency.new(@klass, including, [])
  214
+    end
  215
+
210 216
     def construct_relation_for_association_calculations
211 217
       including = (@eager_load_values + @includes_values).uniq
212 218
       join_dependency = ActiveRecord::Associations::JoinDependency.new(@klass, including, arel.froms.first)
5  activerecord/test/cases/finder_test.rb
@@ -74,6 +74,11 @@ def test_exists_with_scoped_include
74 74
     end
75 75
   end
76 76
 
  77
+  def test_exists_does_not_instantiate_records
  78
+    Developer.expects(:instantiate).never
  79
+    Developer.exists?
  80
+  end
  81
+
77 82
   def test_find_by_array_of_one_id
78 83
     assert_kind_of(Array, Topic.find([ 1 ]))
79 84
     assert_equal(1, Topic.find([ 1 ]).length)

0 notes on commit b155fda

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