@@ -332,31 +332,37 @@ def find_by(*args) # :nodoc:
332
332
hash = args . first
333
333
return super unless Hash === hash
334
334
335
- values = hash . values . map! { |value | value . respond_to? ( :id ) ? value . id : value }
336
- return super if values . any? { |v | StatementCache . unsupported_value? ( v ) }
337
-
338
- keys = hash . keys . map! do |key |
339
- attribute_aliases [ name = key . to_s ] || begin
340
- reflection = _reflect_on_association ( name )
341
- if reflection &.belongs_to? && !reflection . polymorphic?
342
- reflection . join_foreign_key
343
- elsif reflect_on_aggregation ( name )
344
- return super
345
- else
346
- name
347
- end
335
+ hash = hash . each_with_object ( { } ) do |( key , value ) , h |
336
+ key = key . to_s
337
+ key = attribute_aliases [ key ] || key
338
+
339
+ return super if reflect_on_aggregation ( key )
340
+
341
+ reflection = _reflect_on_association ( key )
342
+
343
+ if !reflection
344
+ value = value . id if value . respond_to? ( :id )
345
+ elsif reflection . belongs_to? && !reflection . polymorphic?
346
+ key = reflection . join_foreign_key
347
+ pkey = reflection . join_primary_key
348
+ value = value . public_send ( pkey ) if value . respond_to? ( pkey )
349
+ end
350
+
351
+ if !columns_hash . key? ( key ) || StatementCache . unsupported_value? ( value )
352
+ return super
348
353
end
349
- end
350
354
351
- return super unless keys . all? { |k | columns_hash . key? ( k ) }
355
+ h [ key ] = value
356
+ end
352
357
358
+ keys = hash . keys
353
359
statement = cached_find_by_statement ( keys ) { |params |
354
360
wheres = keys . index_with { params . bind }
355
361
where ( wheres ) . limit ( 1 )
356
362
}
357
363
358
364
begin
359
- statement . execute ( values , connection ) . first
365
+ statement . execute ( hash . values , connection ) . first
360
366
rescue TypeError
361
367
raise ActiveRecord ::StatementInvalid
362
368
end
0 commit comments