fed*_*usy 6 ruby mongodb mongoid ruby-on-rails-3
肯定与这个问题有关,但由于没有明确的答案,我觉得我应该再问一次。有没有办法从 Mongoid embeds_many 关系中删除嵌入的文档,而无需持久化?
我想修改内存中的嵌入文档数组 - 然后使用单个 UPDATE 操作保留所有更改。具体来说,我想:
可以使用 Mongoid 删除嵌入文档而不保存。诀窍是使用 来从父对象进行更改assign_attributes。例如:
class MyParent
include Mongoid::Document
field :name, type: String
embeds_many :my_children
def remove_my_child(child)
assign_attributes(my_children: my_children.select { |c| c != child })
end
end
class MyChild
include Mongoid::Document
embedded_in :my_parent
def remove
parent.remove_my_child(self)
end
end
my_parent = MyParent.first
my_first_child = my_parent.my_children.first
# no mongo queries are executed
my_first_child.remove
# now we can make another change with no query executed
my_parent.name = 'foo'
# and finally we can save the whole thing in one query which is the
# reason we used an embedded document in the first place, right?
my_parent.save!
Run Code Online (Sandbox Code Playgroud)