Difference between Destroy and Delete
Solution 1:
Basically destroy
runs any callbacks on the model while delete
doesn't.
From the Rails API:
-
ActiveRecord::Persistence.delete
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.
The row is simply removed with an SQL DELETE statement on the record's primary key, and no callbacks are executed.
To enforce the object's before_destroy and after_destroy callbacks or any :dependent association options, use #destroy.
-
ActiveRecord::Persistence.destroy
Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can't be persisted).
There's a series of callbacks associated with destroy. If the before_destroy callback return false the action is cancelled and destroy returns false. See ActiveRecord::Callbacks for further details.
Solution 2:
delete
will only delete current object record from db but not its associated children records from db.
destroy
will delete current object record from db and also its associated children record from db.
Their use really matters:
If your multiple parent objects share common children objects, then calling destroy
on specific parent object will delete children objects which are shared among other multiple parents.
Solution 3:
When you invoke destroy
or destroy_all
on an ActiveRecord
object, the ActiveRecord
'destruction' process is initiated, it analyzes the class you're deleting, it determines what it should do for dependencies, runs through validations, etc.
When you invoke delete
or delete_all
on an object, ActiveRecord
merely tries to run the DELETE FROM tablename WHERE conditions
query against the db, performing no other ActiveRecord
-level tasks.