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.
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? There is no difference between the two; :dependent => :destroy and :dependent => :delete_all are semantically equivalent.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With