"first!" AR CollectionProxy raises the "undefined method [] for nil" after upgrading from Rails 4.1.4 to 4.2.0

I am starting to upgrade from Rails 4.1.4 to Rails 4.2.0. This is like the first! is no longer supported in some active record associations.

What happened to first! (in ActiveRecord :: Associations :: CollectionProxy) to cause it to crash now?

How can I fix the behavior the way it works in 4.1.4?

Rails 4.1:

 (byebug) user.organization.registration_codes #<ActiveRecord::Associations::CollectionProxy [#<RegistrationCode id: 259, code: "AWESOMESAUCE" ... >]> (byebug) user.organization.registration_codes.first! #<RegistrationCode id: 259, code: "AWESOMESAUCE" ... > 

Rails 4.2:

 (byebug) user.organization.registration_codes #<ActiveRecord::Associations::CollectionProxy [#<RegistrationCode id: 259, code: "AWESOMESAUCE" ... >]> (byebug) user.organization.registration_codes.first! NoMethodError Exception: undefined method `[]' for nil:NilClass nil 

Update

Digging into ActiveRecord, I find that it does not work here:

 def find_nth(index, offset) if loaded? @records[index] else offset += index @offsets[offset] ||= find_nth_with_limit(offset, 1).first end end 

loaded? returns true, but @records is nil. find_nth_with_limit(offset, 1).first debugger and calling find_nth_with_limit(offset, 1).first returns the expected record.

first! defined in finder_methods.rb in the active record , it seems the problem is that the association considers it loaded, but @records is zero

+5
source share
1 answer

This is regression in Rails. Calling one of the distortion search methods in the loaded collection in rails 4.2 does not work.

https://github.com/rails/rails/issues/18237

+2
source

Source: https://habr.com/ru/post/1209798/


All Articles