CollectionProxy与AssociationRelation [英] CollectionProxy vs AssociationRelation
问题描述
我想知道 ActiveRecord :: Associations :: CollectionProxy
和 ActiveRecord :: AssociationRelation
之间的区别。 / p>
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#=> #< ActiveRecord :: Associations :: CollectionProxy []>
v.wheels.all#=> ; #< ActiveRecord :: AssociationRelation []>
我不知道它们之间有什么区别,以及为什么以这种方式实现?
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
但这是最基本的用法,您可以使用集合代理中公开的属性,这些属性是所有者
,反射
和目标
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
所有者
提供了对持有关联的父对象的引用
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.
目标
是关联集合对象(或单个o当 has_one
和属于
时被拒绝。)
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
)更为常见,它用于重置
,然后从数据库中加载关联的对象。
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与AssociationRelation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!