How can I delete child objects when the parent is deleted in rails?

James picture James · Feb 4, 2010 · Viewed 15.6k times · Source

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.

Answer

hobodave picture hobodave · Feb 4, 2010

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.