Does Active Record's dependent: :destroy also delete the database records?
e.g. dependent: :delete
Does Active Record's dependent: :destroy also delete the database records?
e.g. dependent: :delete
Yes, both will delete the database records but doing it in a different way.
You can check the answer for this question here:
Rails :dependent => :destroy VS :dependent => :delete_all
Basically dependent: :delete
will execute the delete for the dependent records directly on the database without executing any activerecod validations or callbacks.
While dependent: :destroy
will instantiate all the dependent records and execute a :destroy
for each object (executing validations and callbacks).
The :destroy option loads each dependent record from the database and calls the destroy method of that object. The :delete option deletes each record directly from the database without calling destroy or any callbacks.
Documentation for each association type can be found here:
belongs_to: https://guides.rubyonrails.org/association_basics.html#options-for-belongs-to-dependent
has_one: https://guides.rubyonrails.org/association_basics.html#options-for-has-one-dependent
has_many: https://guides.rubyonrails.org/association_basics.html#dependent
What does Delete do?
Delete Documentation 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?
Destroy Documentation 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).