57

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

August Lilleaas
  • 54,010
  • 13
  • 102
  • 111
blogofsongs
  • 2,527
  • 4
  • 21
  • 26

3 Answers3

103

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.

blogofsongs
  • 2,527
  • 4
  • 21
  • 26
  • Indeed! I had a similar issue except I was getting foreign key errors even though I was using `dependent: :destroy`. Problem was I was using `obj.delete` instead of `obj.destroy` so the dependents weren't getting deleted, thus the integrity error. – Tim Fletcher Nov 07 '17 at 18:02
12

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.

drosis
  • 211
  • 4
  • 9
8

If you have a polymorphic association, you should do what @blogofsongs said but with a foreign_key attribute like so:

class User < ActiveRecord::Base
  has_many :activities , dependent: :destroy, foreign_key: :trackable_id
end
rizidoro
  • 13,073
  • 18
  • 59
  • 86