In Mongoid, how do I transfer an embedded document to a different parent?
I am using the following code below, but I would prefer not to ha开发者_开发技巧ve to delete/copy. I used to be able to change the parent ID, but that doesn't exist for embedded documents in Mongoid/MongoDB
def move(new_parent)
if self._parent != new_parent
copy = self.dup
self.delete
new_parent.items << copy
end
end
My understanding is the embedded documents are stored as attributes inside your parent documents - they don't have parent_ids, since they are actually part of their parent (hence, 'embedded'). As such, the only way to reparent them would be to clone & delete - as you've done.
You could probably cut your method down by one line, but that's about it.
def move(new_parent)
unless new_parent.id == parent.id
new_parent.items << self.dup
self.delete
end
end
精彩评论