Unique Marketing, Guaranteed Results.

ActiveRecord Destroy vs. Delete

April 2nd, 2009 by Chuck Wood

I’ve been reading “Pro ActiveRecord” by Kevin Marshall, Chad Pytel, and Jon Yurek. They explained in the book the difference between the delete and destroy methods, which is something I had never really seen clarified anywhere. I’ve discussed it with several Rails developers and have gotten varying opinions.

Here’s what I’ve come to understand. The destroy method makes the SQL call to the database and destroys the row in the table that contains it. It does still allow you to manipulate the object in the application as long as it’s still in scope.

The delete method also makes the SQL call, but freezes the object so you cannot make changes to it. It also doesn’t make the before_destroy and after_destroy callbacks.

Be Sociable, Share!
Filed under: Programming — Tags: , — Chuck Wood @ 9:11 am on April 2, 2009

4 Comments

  1. So no methods do both? We should make a new method called: erased! or annihilated! or vaporized!

    And submit it as a patch to rails!!! :-)

    Comment by jaredd — April 2, 2009 @ 9:18 am

  2. I was thinking more along the lines of ActiveRecord::Base.demolish!

    Comment by chuckw — April 2, 2009 @ 11:04 am

  3. One notable behavioral difference: if you have an association which uses the :dependent option (e.g. :dependent => :delete_all or :dependent => :destroy), the cascading behavior you specify in that option is triggered only if you call destroy on the object that has the association. Calling delete will delete the object at hand (with the freeze behavior mentioned above) – but the associated objects will not be deleted.

    Comment by jeffs — October 19, 2010 @ 7:19 pm

  4. Once you destroy a record, the object becomes frozen. Call the frozen? method on the referenced object before and after calling destroy to see the difference. If you try to manipulate the object after the object is ‘frozen’, you’ll get a TypeError: can’t modify frozen hash

    Comment by Navid — April 12, 2011 @ 3:54 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment

Copyright © 2005-2014 PMA Media Group. All Rights Reserved