Short answer: yes.
Long answer: yeess.
The difference is a little nuanced and not always necessary. Let’s lay out what each method does first, and then we can start the debate about the preferred way to do things.
What does Delete do?
As always, let’s start with the documentation. This is what ActiveRecord does when calling the delete method:
In basic terms, using delete removes the row in the database using a primary key matching the id argument, using a SQL DELETE statement, and returns the number of rows deleted. You can delete multiple rows at once by passing an Array of ids. But when calling delete, that’s it. Nothing else behind the scenes happens.
What does Destroy do?
Again, here is the documentation for our method:
As you can see, using destroy also removes a given id (or ids) from a table. However, an object is instantiated first, therefore all callbacks and filters are fired off before the object is “deleted”. Because of the extra callbacks and validations performed before the object is “deleted”, this method is less efficient than ActiveRecord#delete, but it allows cleanup methods and other actions to be run. Essentially, this finds the given id, creates a new object from the attributes, and then calls destroy on it (performing any dependencies and callbacks).
This flexibility gives can be shown using relationships and dependents. Through ActiveRecord, when establishing has_many/belongs_to relationships, you can also destroy associated data when calling destroy on an object, if you choose to.
:dependent => :destroy_all
has_many :products :dependent => :destroy_all
has_many :lists :dependent => :destroy_all
has_many :friends :dependent => :destroy_all
has_many :buytogethers :dependent => :destroy_all
has_many :comments :dependent => :destroy_all
Additionally, you can perform an action using callbacks such as:
- before_destroy - around_destroy - after_destroy
So…should I always destroy then?
Not necessarily. Each method has purpose, and depending on what you’re trying to accomplish with your data, you’ll likely use both throughout your application.
The easiest way to sum it up is to use delete if you want records to be deleted quickly. However, if you care about models callbacks, referential integrity, or validations (for example, setting a criteria to not destroy a record unless a certain condition is “true”), then use destroy.
In addition, there is always debate within the coding community (or at least that one guy on Stack Overflow that thinks you’re wrong). To see what kind of complications using callback methods can create, see Flatiron’s own David Chase’s blog on callbacks. Callbacks can give you lots of flexibility within your application, but it can also add unneeded complications that can end up making debugging and testing your code difficult.
Like everything else, educate yourself and use your best judgement. And by that, I mean google it.