Tag Archives: rails

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.