ActiveRecord :: Associations :: CollectionProxy从哪里获取.each实例方法?

问题描述 投票:5回答:2

假设我有模型主题和帖子,其中主题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继承的是什么,除非我遗漏了一些明显的东西。

This page似乎没有告诉我太多,this page也没有。

ruby-on-rails ruby activerecord rails-activerecord
2个回答
6
投票

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的工作原理。


4
投票

你为什么不试着问它从何而来?

activerecord/lib/active_record/relation/delegation.rb#L45

Understanding Ruby and Rails: Delegate方法:

返回定义方法的类或模块。

所以delegate来自> ActiveRecord::Associations::CollectionProxy.instance_method(:each).owner => ActiveRecord::Delegation 。如果你看看UnboundMethod#ownereach

ActiveRecord::Delegation

所以ActiveRecord::Delegation进一步受到you'll see this的惩罚。

© www.soinside.com 2019 - 2024. All rights reserved.