Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dependent => destroy on a "has_many through" association

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

like image 472
blogofsongs Avatar asked Sep 09 '09 12:09

blogofsongs


People also ask

What is the difference between dependent => destroy and dependent => Delete_all in Rails?

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).

How does dependent destroy work?

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.

What is dependent destroy?

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.

What is association in Ruby on Rails?

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.


2 Answers

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.

like image 151
blogofsongs Avatar answered Sep 19 '22 14:09

blogofsongs


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.

like image 23
drosis Avatar answered Sep 18 '22 14:09

drosis