views:

146

answers:

3

I have a model called MyContainer, which :has_many MyObjects.

I want to delete all the MyObjects in the container without having to delete the MyContainer. My model does have :dependent => :destroy, however I don't want to have to delete and re-create 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 accomplish this?

A: 

One or both of these should work:

MyContainer.find(10).my_objects.destroy_all

MyContainer.find(10).my_objects.each(&:destroy)
rspeicher
+3  A: 

delete_all is an ActiveRecord::Base class method.

You should use destroy_all. Something like:

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

Using delete_all properly would be faster if you don't need to lookup your MyContainer first (or use it for other stuff)

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

You can delete objects directly like following

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