Mondoid deleting embedded documents is not saved

For several hours, I ran into a problem and I felt pointless.

I have a Mongoid model with an embedded document, for example:

embeds_many :tags, :as => :taggable

      

For some reason, trying to delete this document works on the console, but then the documents come back after reboot. I've tried the following:

model.tags.delete_all

model.tags.each do |tag|
  tag.delete
end

model.tags.destroy_all

      

After all the above, I can confirm that model.tags returns an empty array. Then, to be on the safe side, I even call model.save. If I reload the model, all inline tags return.

What is the correct way to delete inline documents with Mongoid?

+3


source to share


1 answer


Well, it's very simple, but difficult ...

When removing 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 way your model will be reloaded and you will get the correct object

+7


source







All Articles