delete_all vs destroy_all? delete_all vs destroy_all? ruby ruby

delete_all vs destroy_all?


You are right. If you want to delete the User and all associated objects -> destroy_allHowever, if you just want to delete the User without suppressing all associated objects -> delete_all

According to this post : Rails :dependent => :destroy VS :dependent => :delete_all

  • 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


delete_all is a single SQL DELETE statement and nothing more. destroy_all calls destroy() on all matching results of :conditions (if you have one) which could be at least NUM_OF_RESULTS SQL statements.

If you have to do something drastic such as destroy_all() on large dataset, I would probably not do it from the app and handle it manually with care. If the dataset is small enough, you wouldn't hurt as much.


To avoid the fact that destroy_all instantiates all the records and destroys them one at a time, you can use it directly from the model class.

So instead of :

u = User.find_by_name('JohnBoy')u.usage_indexes.destroy_all

You can do :

u = User.find_by_name('JohnBoy')UsageIndex.destroy_all "user_id = #{u.id}"

The result is one query to destroy all the associated records