Ruby activerecord : Difference between delete_all and destroy_all

17 Apr 2012

delete_all

        Delete method, deletes the records matching conditions without instantiating the records , using a SQL DELETE statement, and returns the number of rows deleted. They won't call destroy method nor invoking callbacks. They are much efficient than destroy_all. They won't honor the rules defined on relations with :dependent.

  • No instantiation of records
  • Callbacks are not invoked
  • Efficient
  • Using a single direct SQL DELETE statement
  • :dependent rules defined on associations are not executed.
  • Returns number of rows deleted.

destroy_all

      The destroy method, destroys the records matching conditions by instantiating each record. It returns a collection of objects which they are destroyed, but the returned objects will be frozen so that no changes could be made on it. They execute callbacks and :dependent rules. They are inefficient compared to delete_all since they may use more than 1 SQL statement to destroy a record, which depends on callback. 

  • Instantiate each record
  • Callbacks are invoked
  • Inefficient
  • More than 1 query used, depends on callbacks
  • :dependent rules defined on associations are executed.
  • Returns collection of objects
If you find my work helpful, You can buy me a coffee.