【问题标题】:Where does ActiveRecord::Associations::CollectionProxy get the .each instance method?ActiveRecord::Associations::CollectionProxy 在哪里获取 .each 实例方法?
【发布时间】:2015-07-11 02:46:18
【问题描述】:

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

如果我进入 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


    【解决方案1】:

    ActiveRecord::Associations::CollectionProxyis inherited from RelationRelation转发each和许多其他方法到to_a

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

    委托:to_xml、:to_yaml、:length、:collect、:map、:each、:all?、:include?、:to_ary、:join、到:to_a

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

    【讨论】:

      【解决方案2】:

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

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

      UnboundMethod#owner 方法:

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

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-18
        • 2014-04-26
        • 1970-01-01
        • 1970-01-01
        • 2018-03-02
        • 1970-01-01
        相关资源
        最近更新 更多