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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With