Reputation: 485
I have been running into an issue for hours and have Googled myself senseless.
I have a Mongoid model with an embedded document, like so:
embeds_many :tags, :as => :taggable
For some reason, attempting to delete this document appears to work in the console but then the documents come back after a reload. I have tried the following:
model.tags.delete_all
model.tags.each do |tag|
tag.delete
end
model.tags.destroy_all
After all of the above, I can confirm that model.tags returns an empty array. Then to be safe, I even call model.save. If I reload the model, all of the embedded tags come back.
What is the correct way to delete embedded documents using Mongoid?
Upvotes: 3
Views: 2423
Reputation: 4780
Well Its very simple but tricky ...
When you delete the tags , You need to reload the parent object.
Code
model.tags.delete_all
model.reload
model.tags.each do |tag|
tag.delete
end
model.reload
model.tags.destroy_all
model.reload
This is the way your model will be reloaded and you will get right object
Upvotes: 7