Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid dependent :destroy vs :delete

When using Mongoid referenced reletions what's the diffrence between dependent detroy and dependent delete since in the docs it tells:

:delete: Delete the child documents.
:destroy: Destroy the child documents.
like image 537
Matteo Pagliazzi Avatar asked Mar 31 '12 14:03

Matteo Pagliazzi


People also ask

What is difference between destroy and delete?

Basically destroy runs any callbacks on the model while delete doesn't. Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can't be persisted). Returns the frozen instance.

What is the difference between dependent => destroy and dependent => Delete_all in rails?

What is the difference between :dependent => :destroy and :dependent => :delete_all in Rails? There is no difference between the two; :dependent => :destroy and :dependent => :delete_all are semantically equivalent.

What is dependent destroy in rails?

Dependent is an option of Rails collection association declaration to cascade the delete action. The :destroy is to cause the associated object to also be destroyed when its owner is destroyed.

How do you destroy in rails?

Rails delete operation using destroy methodBy using destroy, you can delete the record from rails as well as its other existing dependencies. So in the context of our rails application, if we delete a book record using the destroy function, the authors associated with the book will also be deleted.


2 Answers

In Mongoid (and also ActiveRecord I believe), delete just removes the object from the database. destroy will delete the object and run all of the appropriate callbacks that the model has defined. So if you have a before_destroy callback on a model and you delete an instance of that model, the before_destroy callback will not be called.

So dependent: :destroy runs the model's callbacks when deleting and dependent: :delete does not.

like image 68
Jeff Smith Avatar answered Sep 19 '22 08:09

Jeff Smith


  • destroy runs model callbacks and then makes a REMOVE query to the DB.
  • delete just makes a REMOVE query to the DB.

The names are taken from ActiveRecord, that's why they don't match mongo very well.

You could see delete as an optimization over destroy. When you use destroy, you make sure that before_destroy callbacks are executed, so proper cleanup is done. In the other hand, if you do something like Model.destroy_all, it has to load ALL elements, and then make a REMOVE query for each of them, whether Model.delete_all makes just one query.

like image 41
tothemario Avatar answered Sep 18 '22 08:09

tothemario