Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 为什么我要打电话给;“业主”;在“a”中;“你有很多”;关系不正常?_Ruby On Rails_Activerecord_Rails Activerecord - Fatal编程技术网

Ruby on rails 为什么我要打电话给;“业主”;在“a”中;“你有很多”;关系不正常?

Ruby on rails 为什么我要打电话给;“业主”;在“a”中;“你有很多”;关系不正常?,ruby-on-rails,activerecord,rails-activerecord,Ruby On Rails,Activerecord,Rails Activerecord,我使用的是Rails 5.0.7.1,我的CollectionProxy实例应该可以访问“@owner”实例变量: 活动记录中的关联代理是对象之间的中间人 它包含被称为@owner的关联和实际的 关联对象,称为@target。什么样的联想 代理大约在@reflection中可用。这是一个例子 类ActiveRecord::Reflection::AssociationReflection blog.posts中的关联代理在blog中的对象为@owner, 其帖子的集合为@target和@refl

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

活动记录中的关联代理是对象之间的中间人 它包含被称为@owner的关联和实际的 关联对象,称为@target。什么样的联想 代理大约在@reflection中可用。这是一个例子 类ActiveRecord::Reflection::AssociationReflection

blog.posts中的关联代理在blog中的对象为@owner, 其帖子的集合为@target和@reflection对象 表示:有多个宏

此类通过方法_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
当我将
byebug
添加到
def number\u-five
owner.a之间的行时?Post
,我检查了
self
的值,我看到它是
ActiveRecord::Associations::CollectionProxy
,所以我想我在应该定义它的范围内调用
owner

我尝试了
Post.last.comments.instance\u变量
,但没有看到
:@owner
,只有以下内容:

[:@association, :@klass, :@table, :@values, :@offsets, 
:@loaded, :@predicate_builder, :@scope]
comments = Post.last.comments
def comments.get_owner
  self.owner
end
我还尝试了以下方法:

[:@association, :@klass, :@table, :@values, :@offsets, 
:@loaded, :@predicate_builder, :@scope]
comments = Post.last.comments
def comments.get_owner
  self.owner
end
这将返回与上述相同的
namererror

值得一提的是,当我运行
Post.last.comments.class
时,我看到它是
Comment::ActiveRecord\u Associations\u CollectionProxy


考虑到文档的阅读方式,我希望能够从
Post.last.comments
中调用
Post.last.comments.owner
@owner
(我已经尝试过这两种方法),并让它返回
Post.last
的值。我的期望是不正确的,还是我的代码是错误的,还是完全是其他原因?

文档有点混乱。我记得第一次需要从扩展方法中脱离关联时,我不得不花几个小时猜测、阅读Rails源代码并进行实验来解决这个问题

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


我不确定这是“正确的”还是“正式的”方法,但这是我自Rails 4以来一直在做的事情。

确认了上述代码的有效性。如果有一个更规范的,官方的方法来做这件事,那么我洗耳恭听,否则我接受这作为一个答案。同时,我可能会尝试在Rails文档上进行PR,指定
所有者是
@association
上的属性,而不是
CollectionProxy
。然后,核心团队可以确认这是“最好”的方式,也可以提出更好的方式。我会对这样一份公关问题报告的结果感兴趣。如对该问题的措辞或清晰度有任何反馈,将不胜感激。如果核心团队同意变更,将通过PR进行跟进。