【问题标题】:Why is my call to "owner" in a "has_many" relationship not working?为什么我在“has_many”关系中对“所有者”的调用不起作用?
【发布时间】:2018-12-30 00:53:36
【问题描述】:

我使用的是 Rails 5.0.7.1,我在 the docs 中看到我的 CollectionProxy 实例应该可以访问“@owner”实例变量:

Active Record 中的关联代理是对象之间的中间人 拥有关联的 @owner 和实际的 关联对象,称为@target。任何关联的类型 proxy is about 在@reflection 中可用。这是一个实例 类 ActiveRecord::Reflection::AssociationReflection。

blog.posts 中的关联代理将 blog 中的对象作为@owner, 其帖子集合为@target,以及@reflection 对象 代表一个 :has_many 宏。

此类通过 method_missing 将未知方法委托给 @target。

在我的 Rails 应用程序中,我有以下(相当不切实际的)测试代码:

class Post < ApplicationRecord
  has_many :comments  do
    def number_five
      if owner.is_a? Post
        Comment.where(id: 5, post_id: self.id)
      end
    end
  end
end

class Comment < ApplicationRecord
  belongs_to :post
end

当我调用Post.last.commments.number_five 时,我收到以下错误:

NameError (undefined local variable or method `owner' for #
<Comment::ActiveRecord_Associations_CollectionProxy:0x00007fcbb9106120>)

当我将byebug 添加到def number_five 和owner.is_a? Post 之间的行,并检查self 的值时,我看到它是ActiveRecord::Associations::CollectionProxy,所以我认为我我在应该定义的范围内调用owner。

我试过Post.last.comments.instance_variables,没有看到:@owner,只有以下:

[:@association, :@klass, :@table, :@values, :@offsets, 
:@loaded, :@predicate_builder, :@scope]

我还尝试了以下方法:

comments = Post.last.comments
def comments.get_owner
  self.owner
end

这将返回与上述相同的NameError。

不管怎样,当我运行Post.last.comments.class 时,我看到它是Comment::ActiveRecord_Associations_CollectionProxy。

考虑到文档的阅读方式,我希望能够从Post.last.comments(我都尝试过)中调用Post.last.comments.owner 或@owner,并让它返回@987654341 的值@。是我的期望不正确,还是我的代码错误,或者完全是别的什么?

【问题讨论】:

    标签: ruby-on-rails activerecord rails-activerecord


    【解决方案1】:

    文档有点混乱。我记得当我第一次需要从扩展方法中脱离关联时,我不得不花几个小时猜测、阅读 Rails 源代码并尝试弄清楚这一点。

    owner 是您所追求的,但这是关联上的一种方法,您可以通过 proxy_association 获得关联(这只是 @association 的访问器方法):

    has_many :comments  do
      def number_five
        if proxy_association.owner.is_a? Post
          #...
        end
      end
    end
    

    我不确定这是执行此操作的“正确”还是“官方”方式,但这是自 Rails 4 以来我一直在做的事情。

    【讨论】:

    • 确认上述代码有效。如果有更规范的官方方式来做到这一点,那么我会全神贯注,否则我会接受这个作为答案。同时,我可能会尝试在 Rails 文档上进行 PR,指定 owner 是 @association 上的属性,而不是 CollectionProxy 上的属性。然后核心团队可以确认这是“最佳”方式或提出更好的方式。
    • 我会对这样的 PR 的结果感兴趣。
    • 在这里发布问题报告-github.com/rails/rails/issues/34829。对问题的措辞或清晰度的任何反馈将不胜感激。如果核心团队同意更改,将跟进 PR。
    猜你喜欢
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 2017-09-12
    相关资源
    最近更新 更多