我开始从 Rails 4.1.4 升级到 Rails 4.2.0。好像是第一个!某些活动记录关联不再支持。
(在 ActiveRecord::Associations::CollectionProxy 上)发生了什么first!
导致它现在失败?
如何修复该行为,使其像 4.1.4 一样工作?
导轨 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" ... >
导轨 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
更新
深入研究 ActiveRecord,我发现它在这里失败了:
def find_nth(index, offset)
if loaded?
@records[index]
else
offset += index
@offsets[offset] ||= find_nth_with_limit(offset, 1).first
end
end
loaded?
返回 true,但 @records 为零。投入调试器并调用find_nth_with_limit(offset, 1).first
会返回我期望的记录。
first!
在活动记录中的 finder_methods.rb 中定义问题似乎是协会认为它已加载,但@records 为 nil