目前我正在开发一个 gem,它会覆盖 ActiveRecordswhere
。通过研究,我偶然发现了两种不同的find_by
实施。一个是在core https://github.com/rails/rails/blob/5-0-stable/activerecord/lib/active_record/core.rb#L182它使用某种缓存,而来自FinderMethods https://github.com/rails/rails/blob/5-0-stable/activerecord/lib/active_record/relation/finder_methods.rb#L77模块调用where
直接地。这两种实现有什么区别?什么时候用哪个?
我认为是这样的:当你使用这样的东西时:
User.find_by(...)
The ActiveRecord::Core#find_by
被调用,因为 Core 包含在您继承的 Base 中。
但如果你做类似的事情:
User.first.products.find_by(...)
ActiveRecord::Relation(包括FinderMethods
here https://github.com/rails/rails/blob/c9061254de48437924293ef0e797365527107dc1/activerecord/lib/active_record/relation.rb#L16) 将会通知FinderMethods#find_by
我不知道为什么要这样实施,但我确信这是有原因的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)