Monthly Archives: March 2014

Destroy vs Delete in Rails

It has been not really clear in my mind the difference between “destroy” and “delete” for a while before attempting to delete an object and its related once. In this situation and, reading carefully the documentation and the source code, I have discovered that was impossible since delete is used to delete the objects without instantiating it and executing the callbacks, including :dependent for associations. While using destroy the object is instantiated first and so callbacks and filters are triggered.

Assuming the existence of two model a Customer and an Address. With a relation of has_many that connects them:

class Customer < ActiveRecord::Base
has_many :addresses, dependent: :destroy
end
class Address < ActiveRecord::Base
belongs_to :customer
end

I’ve tried to use delete to remove the customer from the database but all the addresses were pending in the database orphans. Then I’ve used “destroy” to destroy the customer and all the addresses related.

Customer.destroy(params[:id])

In this way the customer and all the addresses (marked using “dependent” option) are deleted.

Ruby and its destructive methods…

In ruby there are methods followed by a “!” symbol (exclamation mark). These methods alter the object itself.

For example in the Array class there are two versions of shuffle method
shuffle and shuffle!.

a = [1,2,3, 4] => [1, 2, 3, 4]
a.object_id => 70279519801380
a.shuffle.object_id => 70279519867040
a.shuffle!.object_id => 70279519801380

  • Shuffle version returns a new array with elements of self shuffled and as a.shuffle.object_id shows a different value from a.object_id.
  • shuffle! modifies the object itself,¬† shuffling elements in self in place and a.shuffle!.object_id shows the same object_id of a.object_id.