Rails, Deleting Children without Deleting Parent using :has_many
Asked Answered
M

3

8

I have

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

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?

Millais answered 20/4, 2010 at 7:4 Comment(0)
P
28

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])

EDIT: for rails 3

MyObject.where(my_container_id: 10).delete_all
Phillis answered 20/4, 2010 at 7:10 Comment(0)
Q
0

One or both of these should work:

MyContainer.find(10).my_objects.destroy_all

MyContainer.find(10).my_objects.each(&:destroy)
Quiz answered 20/4, 2010 at 7:8 Comment(2)
Using the latter, solution would load each object into memory and be slow. Probably want to go with first solution.Baggywrinkle
Both with instantiate each object into memory.Chlorella
P
0

You can delete objects directly like following

MyObject.delete_all(["my_container_id=?", 10])
Primate answered 20/4, 2010 at 7:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.