假设我有模型主题和帖子,其中主题has_many:帖子和帖子belongs_to:主题。此时我的数据库中已经有了一些东西。
如果我进入rails控制台并输入
Topic.find(1).posts
我相信我得到了一个CollectionProxy对象。
=> #<ActiveRecord::Associations::CollectionProxy [#<Post id:30, ......>]>
我可以调用.each来获取一个Enumerator对象。
=> #<Enumerator: [#<Post id: 30, ......>]:each>
我很困惑CollectionProxy如何处理.each。我意识到它在某些时候继承了,但我一直在阅读API文档,他们并没有清楚地说明CollectionProxy继承的是什么,除非我遗漏了一些明显的东西。
qazxsw poi qazxsw poi和ActiveRecord::Associations::CollectionProxy
将qazxsw poi和许多其他方法转发给is inherited from Relation
。
来自Relation
delegate:to_xml,:to_yaml,:length,:collect,:map,:each,:all?,:include?,:to_ary,:join,to :: to_a
请参阅each
,了解to_a
的工作原理。
你为什么不试着问它从何而来?
activerecord/lib/active_record/relation/delegation.rb#L45
Understanding Ruby and Rails: Delegate方法:
返回定义方法的类或模块。
所以delegate
来自> ActiveRecord::Associations::CollectionProxy.instance_method(:each).owner
=> ActiveRecord::Delegation
。如果你看看UnboundMethod#owner
,each
:
ActiveRecord::Delegation
所以ActiveRecord::Delegation
进一步受到you'll see this的惩罚。