Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 895
James Avatar asked Feb 04 '10 22:02

James


People also ask

How do I delete an object in rails?

By using destroy, you can delete the record from rails as well as its other existing dependencies. So in the context of our rails application, if we delete a book record using the destroy function, the authors associated with the book will also be deleted.

What is the difference between delete and destroy in rails?

Basically destroy runs any callbacks on the model while delete doesn't. Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can't be persisted). Returns the frozen instance.

What is dependent destroy in rails?

If you set the :dependent option to: :destroy, when the object is destroyed, destroy will be called on its associated objects. :delete, when the object is destroyed, all its associated objects will be deleted directly from the database without calling their destroy method.


1 Answers

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.

like image 152
hobodave Avatar answered Sep 18 '22 15:09

hobodave