James
James

Reputation: 5393

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

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.

Upvotes: 19

Views: 19496

Answers (1)

hobodave
hobodave

Reputation: 29293

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.

Upvotes: 45

Related Questions