Ruby-on-rails 依赖 => 销毁“has_many through”关联
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1399394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
dependent => destroy on a "has_many through" association
提问by blogofsongs
Apparently dependent => destroy is ignored when also using the :through option.
当还使用 :through 选项时,显然依赖 => destroy 会被忽略。
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.
...但删除评论不会导致关联的 comment_user 记录被删除。
What's the recommended approach, then, for cascade deletes when using :through?
那么,在使用 :through 时进行级联删除的推荐方法是什么?
Thanks
谢谢
回答by blogofsongs
Apparently :dependent is not ignored!
显然 :dependent 没有被忽略!
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 => :destroyand all is well.
真正的问题是我正在调用Comment.delete(id)which 直接进入数据库,而我现在使用Comment.destroy(id)which 加载 Comment 对象并对其调用 destroy() 。这:dependent => :destroy一切都很好。
回答by drosis
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.
原始海报的解决方案是有效的,但是我想指出这仅在您有该表的 id 列时才有效。我更喜欢我的多对多表只是两个外键,但我必须从迁移表定义中删除我的“id:false”,以便级联删除工作。拥有此功能绝对比没有表上的 id 列更重要。
回答by rizidoro
If you have a polymorphic association, you should do what @blogofsongs said but with a foreign_key attribute like so:
如果你有一个多态关联,你应该像@blogofsongs 所说的那样做,但有一个foreign_key 属性,如下所示:
class User < ActiveRecord::Base
has_many :activities , dependent: :destroy, foreign_key: :trackable_id
end

