CollectionProxy vs AssociationRelation [英] CollectionProxy vs AssociationRelation
问题描述
我想知道 ActiveRecord::Associations::CollectionProxy
和 ActiveRecord::AssociationRelation
之间的区别.
I am wondering about the difference between ActiveRecord::Associations::CollectionProxy
and ActiveRecord::AssociationRelation
.
class Vehicle < ActiveRecord::Base
has_many :wheels
end
class Wheel < ActiveRecord::Base
belongs_to :vehicle
end
如果我这样做:
v = Vehicle.new
v.wheels # =>#
v.wheels.all # =>#
我不知道它们之间有什么区别以及为什么以这种方式实现?
I have no idea what is the difference between them and why this is implemented this way?
推荐答案
ActiveRecord::Relation
在变成查询并执行之前是简单的查询对象,CollectionProxy
在另一只手稍微复杂一些.
ActiveRecord::Relation
are simple query objects before being turned into a query and executed, CollectionProxy
on the other hand are a little bit more sophisticated.
首先你会得到关联扩展,你可能看到过类似这样的东西,假设一个有很多书的书店模型
First of all you get association extentions, you probably saw something that looks like this, assume a book store model that has many books
class Store < ActiveRecord::Base
has_many :books do
def used
where(is_used: true)
end
end
end
这样你就可以使用类似这样的语法调用商店中的旧书
This way you get to call used books in a store using a syntax that looks like this
Store.first.books.used
但这是最基本的用途,您可以使用集合代理中暴露给您的属性,它们是owner
、reflection
和target
But this is the most basic uses, you could use the attributes that are exposed to you in the collection proxy, which are owner
, reflection
and target
owner
提供对持有关联的父对象的引用
The owner
provides a a reference to the parent object holding the association
reflection
对象是 ActiveRecord::Reflection::AssocciationReflection
的一个实例,包含关联的所有配置选项.
The reflection
object is an instance of ActiveRecord::Reflection::AssocciationReflection
and contains all the configuration options for the association.
target
是关联集合对象(当has_one
和belongs_to
时为单个对象).
The target
is the association collection objects (or single object when has_one
and belongs_to
).
使用这些方法,您可以在关联扩展中设置一些条件,例如,如果我们有一个博客,我们会将所有已删除帖子的访问权限授予管理员用户(我知道这是一个蹩脚的例子)
Using those methods you could do some conditons in your association extention, for example if we have a blog, we give access to all deleted posts to users who are admins (lame example I know)
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
您还可以访问另外两个方法,它们是 reset
和 reload
,第一个 (reset
) 清除缓存的关联对象,第二个(reload
)比较常用,用于reset
然后从数据库中加载关联的对象.
You also get access to two more methods which are reset
and reload
, the first one (reset
) clears the cached association objects, the second one (reload
) is more common and is used to reset
and then loads the associated objects from the database.
我希望这可以解释 CollectionProxy
类如何如此有用
I hope this explains how having a CollectionProxy
class would be so useful
这篇关于CollectionProxy vs AssociationRelation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!