ActiveRecord::Associations::CollectionProxy 从哪里得到 .each 实例方法?

Where does ActiveRecord::Associations::CollectionProxy get the .each instance method?

假设我有模型 Topics 和 Posts,其中 Topic has_many :posts 和 Post belongs_to :topic。此时我的数据库中已经有一些东西了。

如果我进入 rails 控制台并输入

Topic.find(1).posts

我想我找回了一个 CollectionProxy 对象。

=> #<ActiveRecord::Associations::CollectionProxy [#<Post id:30, ......>]>

我可以调用 .each 来获取枚举器对象。

=> #<Enumerator: [#<Post id: 30, ......>]:each>

我对 CollectionProxy 如何处理 .each 感到困惑。我意识到它在某些时候是继承的,但我一直在阅读 API 文档,他们并没有说得很清楚 CollectionProxy 是从什么继承的,除非我遗漏了一些明显的东西。

This page doesn't seem to tell me much, and neither does this page.

ActiveRecord::Associations::CollectionProxy is inherited from RelationRelationeach 和许多其他方法转发到 to_a.

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

delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to_ary, :join, to: :to_a

有关 delegate 工作原理的精彩解释,请参阅 Understanding Ruby and Rails: Delegate

你为什么不试着问问它是从哪里来的呢?

> ActiveRecord::Associations::CollectionProxy.instance_method(:each).owner
=> ActiveRecord::Delegation 

UnboundMethod#owner方法:

Returns the class or module that defines the method.

所以 each 来自 ActiveRecord::Delegation。如果您查看 ActiveRecord::Delegationyou'll see this:

delegate ..., :each, ... , to: :to_a

所以 each 被进一步踢到 to_a.each