views:

759

answers:

2

In rails guides it's described like this: "Objects will be in addition destroyed if they’re associated with :dependent => :destroy, and deleted if they’re associated with :dependent => :delete_all."

Right, cool. But what's the difference between being destroyed and being deleted? I tried both and it seems to do the same thing.

+6  A: 

The difference is with callback.

The :delete_all, made directly in your application the delete by SQL :

DELETE * FROM users where compagny_id = XXXX

With the :destroy, there are an instantiation of all of you children. So, if you can't destroy it or if each has their own :dependent, its can be called.

shingara
The instantiation and the calling of destroy on each of the children objects will be slow if you have a lot of children (and n^2 if you have grandchildren, and so on). delete_all is the kind of "nuke it from orbit" solution where you don't care about / don't have any before / after destroy callbacks on the models.
Ryan Bigg
+5  A: 

On a Rails' model association you can specify the :dependent option, which can take one of the following three forms:

  • :destroy/:destroy_all The associated objects are destroyed alongside this object by calling their destroy method
  • :delete/:delete_all All associated objects are destroyed immediately without calling their :destroy method
  • :nullify All associated objects' foreign keys are set to NULL without calling their save callbacks
John Topley