19

model a:

has_many :b, :dependent => :delete_all

model b:

belongs_to :a
belongs_to :c

model c:

has_many :b

When I delete an a, I would also like to have children b's deleted so that they get removed from any c's that may reference them. However, the above isn't working. I'd appreciate any help.

James
  • 5,273
  • 10
  • 51
  • 76

1 Answers1

46

Like so:

class Widgets < ActiveRecord::Base
  has_many :whatevers, :dependent => :destroy
end

Update

Your recent comment indicates you are using the delete() method to delete your objects. This will not use the callbacks. Please read the manual for specifics.

hobodave
  • 28,925
  • 4
  • 72
  • 77
  • I can't figure out why this isn't working. When I delete an 'a' that references a 'b', and that 'b' is also referenced in a 'c', the 'b' is still a child of the 'c' after deletion of 'a', using the above. – James Feb 04 '10 at 23:00
  • James, you'd have to have :dependent => :destroy for all of the objects in the chain. – Mike Buckbee Feb 04 '10 at 23:10
  • hmmm... works when I call destroy on the parent, but doesn't work when I call delete. Is this expected? – James Feb 04 '10 at 23:12
  • @James: Yes this is expected. Delete doesn't use the :dependent callbacks. See: http://www.nickpeters.net/2007/12/21/delete-vs-destroy/ – hobodave Feb 04 '10 at 23:16
  • @james, to be ridiculously clear, `has_many :b, :dependent => :delete_all` will remove all of a's children if you call `a.destroy`. – BM5k Mar 12 '13 at 03:52