Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm starting to upgrade from Rails 4.1.4 to Rails 4.2.0. It looks like first! is no longer supported on some active record associations.

What happened to first! (on ActiveRecord::Associations::CollectionProxy) to cause it to fail now?

How can fix the behavior so it works as 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

Updated

Digging into ActiveRecord, I find it failing 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. Throwing a debugger in and calling find_nth_with_limit(offset, 1).first returns the record that I expect.

first! is defined in finder_methods.rb in active record the issue seems to be that the association thinks its loaded, but @records is nil

like image 200
John Naegle Avatar asked Oct 31 '22 12:10

John Naegle


1 Answers

This is a regression in Rails. Calling one of the bang finder methods on a loaded collection in rails 4.2 does not work.

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

like image 59
John Naegle Avatar answered Nov 08 '22 13:11

John Naegle