1

In Rails document Active Record Associations, The first 2 values of :dependent for has_one are:

4.2.2.4 :dependent

Controls what happens to the associated object when its owner is destroyed:

    :destroy causes the associated object to also be destroyed
    :delete causes the associated object to be deleted directly from the database (so callbacks will not execute)

My understanding about :destroy is for example, a customer has_one address. With :dependent => :destroy, if customer is deleted, then address will be deleted automatically from the database after customer is deleted from the database and we usually use :destroy. What's use of the :delete?

user938363
  • 9,990
  • 38
  • 137
  • 303

2 Answers2

5

Both does almost the same, I said almost, because:

dependent: :destroy - calls callbacks (before_destroy, after_destroy) in associated objects, and then you're able to break the transactions (raise error in callback).

dependent: :delete - doesn't call callbacks (it removes object directly from database by SQL like DELETE FROM ... WHERE ...)

Jan Strnádek
  • 808
  • 5
  • 16
4

In order to complete Jan's answer destroy adds loading of an object to the memory before deleting it (and calling callbacks). Basically there is a quite a a difference, because using delete avoids callbacks/validations and it might breake referential integrity.

delete

Deletes the row with a primary key matching the id argument, using a SQL DELETE statement, and returns the number of rows deleted. Active Record objects are not instantiated, so the object’s callbacks are not executed, including any :dependent association options.

You can delete multiple rows at once by passing an Array of ids.

Note: Although it is often much faster than the alternative, #destroy, skipping callbacks might bypass business logic in your application that ensures referential integrity or performs other essential jobs.

destroy

Destroy an object (or multiple objects) that has the given id. The object is instantiated first, therefore all callbacks and filters are fired off before the object is deleted. This method is less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run.

This essentially finds the object (or multiple objects) with the given id, creates a new object from the attributes, and then calls destroy on it.

http://apidock.com/rails/ActiveRecord/Relation/destroy

For further discussion take a look at this post Difference between Destroy and Delete

Community
  • 1
  • 1
adamliesko
  • 1,887
  • 1
  • 14
  • 21