"第一!" 在从Rails 4.1.4更新到4.2.0之后,AR CollectionProxy引发了"未定义的方法[]为nil"

Joh*_*gle 5 ruby ruby-on-rails ruby-on-rails-4 rails-activerecord ruby-on-rails-4.2

我开始从Rails 4.1.4升级到Rails 4.2.0.它看起来像第一个!某些活动记录关联不再支持.

发生了什么事first!(在ActiveRecord的::协会:: CollectionProxy),使现在失败?

如何修复行为,使其像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" ... >
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

更新

深入研究ActiveRecord,我发现它失败了:

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

loaded?返回true,但@records为零.抛出调试器并调用find_nth_with_limit(offset, 1).first返回我期望的记录.

first!在finder_methods.rb定义在活动记录的问题似乎是,该协会认为其加载,但@records为零

Joh*_*gle 2

这是 Rails 中的回归。在 Rails 4.2 中对已加载的集合调用 bang finder 方法之一不起作用。

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