模块:Mongoid::Copyable
Overview
该模块包含 Mongoid 的 document 克隆/复制行为。
类方法摘要折叠
-
.clone_with_hash(klass, attrs) ⇒ document
使用给定的属性哈希创建给定类的document克隆。
实例方法摘要折叠
-
# clone ⇒ 文档(又作:#dup)
克隆当前的
Document。
类方法详细信息
.clone_with_hash(klass, attrs) ⇒ Document
使用给定的属性哈希创建给定类的document克隆。它以递归方式使用,以便安全地克隆嵌入式关联。
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/mongoid/copyable.rb', 第42行 def self.clone_with_hash(klass, attrs) 动态属性 = {} _attribute_names = klass.attribute_names attrs.拒绝! do |attr_name, 值| 除非 _attribute_names.包括?(attr_name) 动态属性[attr_name] = 值 true end end 工厂.构建(klass, attrs).点击 do |对象| 动态属性.每 do |attr_name, 值| assoc = 对象.[attr_name] if assoc&。一个? && 值.is_a?(哈希) 对象.发送("#{attr_name}=", clone_with_hash(assoc.klass, 值)) elsif assoc&。很多? && 值.is_a?(阵列) docs = 值.map { |h| clone_with_hash(assoc.klass, h) } 对象.发送("#{attr_name}=", docs) elsif 对象.respond_to?("#{attr_name}=") 对象.发送("#{attr_name}=", 值) else 对象.属性[attr_name] = 值 end end end end |
实例方法详细信息
# clone ⇒ Document也称为: dup
克隆当前的 Document。这将返回除 document ID 之外的所有属性,并将重置所有实例变量。
此克隆还包括嵌入式文档。与根文档的_id不同,如果嵌入式文档中有_id字段,则会保留该字段。
如果克隆嵌入式子文档,则不会克隆嵌入式父文档,也不会设立embedded_in 关联。
22 23 24 25 26 27 28 29 |
# File 'lib/mongoid/copyable.rb', 第22行 def 克隆 # @note 下一行是为了解决# 2704 ,即使有 #文档中的_id和ID字段会导致 Mongoid 出现问题 # 其他地方。 请注意,这仅适用于我们想要的根文档 # 在嵌入式文档上保持相同的_id 。 attrs = clone_document.除了(*self.class.id_fields) 可复制.clone_with_hash(self.class, attrs) end |