【发布时间】: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