Jeff Pritchard wrote:
What does "destroy" check for and/or fix up that might get skipped by
I struggled with this just a couple days ago and wound up apparently
picking the wrong one since I couldn't find any documentation (as usual)
for the difference. Just something about "instantiates it first"; and
since I didn't particularly need to instantiate it, I chose "delete".
Every ActiveRecord object can have 'callbacks' associated with it.
These let you attach behaviour to certain points in the object's
lifecycle. For example, you could run validity checks on an object
before it is created, or you could make it so that only objects that
are in a certain state are allowed to be destroyed/deleted. Also, some
of the built-in ActiveRecord facilities (such as :dependent =>
:whatever) internally make use of the callback system to do their dirty
When you use a 'destroy' method to delete an object or objects,
ActiveRecord goes through the full process of creating the object in
memory as an ActiveRecord object (AKA instantiating the object),
checking all the callbacks and running them if appropriate, and
deleting the row from the database.
In pseudo-ruby, calling User.destroy(1) does something like this:
user = User.find(1)
On the other hand, calling a 'delete' method doesn't bother with any of
this. It simply executes a SQL statement to delete the row(s) from the
database, and doesn't give any other bit of ActiveRecord a chance to
get involved. So, calling User.delete(1) does something like this:
As a rule of thumb, I'd say you should always use 'destroy'. I'd only
use 'delete' if I needed to for a specific performance optimisation,
and if I was absolutely sure that the class in question had no
callbacks or similar related behaviour attached to it.