Rails, removing children without removing the parent using: has_many

I have

class MyContainer < ActiveRecord::Base :has_many MyObjects, :dependent => :destroy end 

I want to delete all MyObjects in the container without deleting MyContainer . My model has :dependent => :destroy , but I do not want to delete and recreate the object, because it is slower.

Something like this does not work:

 @obj = MyContainer.find_by_id(10) @obj.my_objects.delete_all 

How can i do this?

+7
ruby-on-rails children has-many
source share
3 answers

delete_all is a method of the ActiveRecord::Base class.

You must use destroy_all . Something like:

 @container = MyContainer.find_by_id(10) @container.my_objects.destroy_all 

Using delete_all correctly will be faster if you don't need to search your MyContainer (or use it for other things)

 MyObject.delete_all(["my_container_id = ?", 10]) 

EDIT: for rails 3

 MyObject.where(my_container_id: 10).delete_all 
+24
source share

One or both of these should work:

 MyContainer.find(10).my_objects.destroy_all MyContainer.find(10).my_objects.each(&:destroy) 
0
source share

You can delete objects as shown below.

 MyObject.delete_all(["my_container_id=?", 10]) 
0
source share

All Articles