Difference between Destroy and Delete
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.
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.
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.
Yes there is a major difference between the two methods Use delete_all if you want records to be deleted quickly without model callbacks being called
If you care about your models callbacks then use destroy_all
From the official docs
http://apidock.com/rails/ActiveRecord/Base/destroy_all/class
destroy_all(conditions = nil) public
Destroys the records matching conditions by instantiating each record and calling its destroy method. Each object’s callbacks are executed (including :dependent association options and before_destroy/after_destroy Observer methods). Returns the collection of objects that were destroyed; each will be frozen, to reflect that no changes should be made (since they can’t be persisted).
Note: Instantiation, callback execution, and deletion of each record can be time consuming when you’re removing many records at once. It generates at least one SQL DELETE query per record (or possibly more, to enforce your callbacks). If you want to delete many rows quickly, without concern for their associations or callbacks, use delete_all instead.