gpt4 book ai didi

ruby-on-rails - CollectionProxy 与 AssociationRelation

转载 作者:数据小太阳 更新时间:2023-10-29 06:38:51 24 4
gpt4 key购买 nike

我想知道 ActiveRecord::Associations::CollectionProxy 之间的区别和 ActiveRecord::AssociationRelation .

class Vehicle < ActiveRecord::Base
has_many :wheels
end

class Wheel < ActiveRecord::Base
belongs_to :vehicle
end

如果我这样做:

v = Vehicle.new

v.wheels # => #<ActiveRecord::Associations::CollectionProxy []>

v.wheels.all # => #<ActiveRecord::AssociationRelation []>

我不知道它们之间有什么区别,为什么要这样实现?

最佳答案

ActiveRecord::Relation 是在转换为查询并执行之前的简单查询对象,另一方面,CollectionProxy 稍微复杂一些。

首先你得到关联扩展,你可能看到了类似这样的东西,假设一个有很多书的书店模型

class Store < ActiveRecord::Base
has_many :books do
def used
where(is_used: true)
end
end
end

这样你就可以使用如下所示的语法调用商店中的旧书

Store.first.books.used

但这是最基本的用途,你可以使用集合代理中暴露给你的属性,它们是ownerreflectiontarget

拥有者

owner 提供对持有关联的父对象的引用

反射(reflection)

reflection 对象是 ActiveRecord::Reflection::AssocciationReflection 的实例,包含关联的所有配置选项。

目标

target 是关联集合对象(或者当has_onebelongs_to 时是单个对象)。

使用这些方法,您可以在您的关联扩展中设置一些条件,例如,如果我们有一个博客,我们会向管理员用户授予对所有已删除帖子的访问权限(我知道的蹩脚示例)

Class Publisher < ActiveRecord::Base
has_many :posts do
def deleted
if owner.admin?
Post.where(deleted: true)
else
where(deleted: true)
end
end
end
end

您还可以访问另外两个方法,它们是 resetreload,第一个 (reset) 清除缓存的关联对象,第二种 (reload) 更常见,用于重置,然后从数据库加载相关对象。

我希望这能解释CollectionProxy 类为何如此有用

关于ruby-on-rails - CollectionProxy 与 AssociationRelation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33683555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com