Apparently dependent => destroy is ignored when also using the :through option.
So I have this...
class Comment < ActiveRecord::Base has_many :comment_users, :dependent => :destroy has_many :users, :through => :comment_users ... end
...but deleting a Comment does not result in the associated comment_user records getting deleted.
What's the recommended approach, then, for cascade deletes when using :through?
Thanks
Therefore, other similar callbacks may affect the :dependent behavior, and the :dependent behavior may affect other callbacks. :destroy causes all the associated objects to also be destroyed. :delete_all causes all the associated objects to be deleted directly from the database (so callbacks will not be executed).
dependent: :destroy Rails, when attempting to destroy an instance of the Parent, will also iteratively go through each child of the parent calling destroy on the child. The benefit of this is that any callbacks and validation on those children are given their day in the sun.
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.
Association in Rails defines the relationship between models. It is also the connection between two Active Record models. To figure out the relationship between models, we have to determine the types of relationship.
Apparently :dependent is not ignored!
The real issue was that I was calling Comment.delete(id)
which goes straight to the db, whereas I now use Comment.destroy(id)
which loads the Comment object and calls destroy() on it. This picks up the :dependent => :destroy
and all is well.
The original poster's solution is valid, however I wanted to point out that this only works if you have an id column for that table. I prefer my many-to-many tables to only be the two foreign keys, but I had to remove my "id: false" from the migration table definition for cascading delete to work. Having this functionality definitely outweighs not having an id column on the table.
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