从Rails 4.1.4升级到4.2.0后,在AR CollectionProxy上使用"first!"会引发"undefined method [] for nil"错误。

5

我开始从Rails 4.1.4升级到Rails 4.2.0。看起来在某些活动记录关联上不再支持first!。

首先,什么导致了在ActiveRecord :: Associations :: CollectionProxy 上的first!失败?

如何修复此行为,使其像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

更新

深入研究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!在active record的finder_methods.rb中定义。问题似乎在于该关联认为已经加载了,但@records为空。

首先!似乎没有被弃用。 - Doon
first! 定义在哪里?因为我在任何文档或来源中都找不到它。 - engineersmnky
它被定义为活动记录查找器的一部分,但似乎不再在集合代理上定义。 - Doon
它在4.1中也没有出现,它必须被委派或复制到Rails的其他地方。无论是它最初的存在还是它的删除都是一个错误 :) 也许可以跳转到Rails核心邮件列表并在那里提问。 - smathy
它在finder_methods.rb中,是Active Record 4.2的第145行左右。问题不在于first!不存在,而在于它无法正常工作。 - John Naegle
1个回答

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接