Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

destroy vs destroy_all

I need to know when to use :dependent => :destroy_all and when to use :dependent => :destroy

What happen if my model has_many child models, and I used :dependent => :destroy ? will it destroy only the first child model ?

is this line of code wrong:

has_many books, :dependent => :destroy

shall it be like this:

has_many books, :dependent => :destroy_all

?

like image 998
simo Avatar asked Jan 06 '13 22:01

simo


1 Answers

This will destroy all books. All of them.

has_many books, :dependent => :destroy

An important thing to remember is that :dependent => :destroy will cause the calling of the #destroy method in each and every one of the associated Books. By calling #destroy on each Book, any before_destroy or after_destroy callback will be executed for each Book.

Naturally, if you have a LOT of dependent books, this process could be expensive.

The :destroy_all is invalid, maybe you were thinking about :delete_all. The difference with :delete_all (instead of just :destroy) is that Rails will issue a single SQL statement to delete all dependent book records. No #destroy method will be called on any Book record, and no before_destroy or after_destroy callback will be executed.

The upside is that a single SQL statement is many times more efficient to delete records from the database than calling #destroy on each one of them.

This is very important to know. If you have any *_destroy callbacks on the Book model, you should be aware that defining :dependent => :delete_all will have the effect of ignoring any callbacks you defined on the Book model.

like image 155
Jorge Gajon Avatar answered Nov 16 '22 13:11

Jorge Gajon