加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – CollectionProxy vs AssociationRelation

发布时间:2020-12-17 04:34:49 所属栏目:百科 来源:网络整理
导读:我想知道ActiveRecord :: Associations :: CollectionProxy和ActiveRecord :: AssociationRelation之间的区别. class Vehicle ActiveRecord::Base has_many :wheelsendclass Wheel ActiveRecord::Base belongs_to :vehicleend 所以,如果我这样做: v = Vehic
我想知道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

但这是最基本的用途,您可以使用在集合代理中公开的属性,即属性,反射和目标

所有者

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

反射

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

目标

目标是关联集合对象(或has_one和belongs_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

您还可以访问另外两个重置和重新加载的方法,第一个(重置)清除缓存的关联对象,第二个(重新加载)更常见,用于重置然后从数据库加载关联的对象.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读