我可以在不保留的情况下删除 Mongoid 中的嵌入文档吗?

fed*_*usy 6 ruby mongodb mongoid ruby-on-rails-3

肯定与这个问题有关,但由于没有明确的答案,我觉得我应该再问一次。有没有办法从 Mongoid embeds_many 关系中删除嵌入的文档,而无需持久化?

我想修改内存中的嵌入文档数组 - 然后使用单个 UPDATE 操作保留所有更改。具体来说,我想:

  1. 修改嵌入式文档数组(添加嵌入式文档/删除嵌入式文档/编辑嵌入式文档等)。
  2. 可能对 TLD 进行其他更改。
  3. 通过单个数据库调用保留所有更改。

Ste*_*sby 4

可以使用 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)