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.

1

1 Answer 1

45

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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, you'd have to have :dependent => :destroy for all of the objects in the chain.
hmmm... works when I call destroy on the parent, but doesn't work when I call delete. Is this expected?
@James: Yes this is expected. Delete doesn't use the :dependent callbacks. See: nickpeters.net/2007/12/21/delete-vs-destroy
@james, to be ridiculously clear, has_many :b, :dependent => :delete_all will remove all of a's children if you call a.destroy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.