如何从 Rails 中的 HABTM 连接表中删除条目?
通过多次迭代测试,我注意到当这些模型的实例被删除时,代表两个模型之间 HABTM 关系的连接表并没有删除条目。删除具有 HABTM 关系的模型实例时,我是否需要执行一些特殊操作?
Through many iterations of testing, I just noticed that my join table that represents a HABTM relationship between two models isn't removing entries when instances of these models get deleted. Do I need to do something special when removing an instance of a model that has HABTM relationships?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
经过仔细检查,HABTM 关系应该删除连接表条目。但是,当您使用
delete
方法删除记录时,HABTM 关系或我在该解决方案的原始版本(请参阅帖子历史记录)中描述的关系都不会删除这些连接表条目。ActiveRecord::Base#delete
不会触发任何回调,例如 HABTM 关系为从连接表中删除孤立条目而建立的回调。相反,您应该使用ActiveRecord::Base#destroy
。您必须使用原始 SQL 来删除不需要的条目。如果您决定创建连接模型,则可以迭代连接模型中的条目,删除那些没有关联的条目。
例子:
Upon closer inspection HABTM relationships should be removing join table entries. However neither HABTM relationships or the relationship I described in the original version (see post history) of this solution will remove those join table entries when you eliminate the record with the
delete
method.ActiveRecord::Base#delete
does not trigger any callbacks, such as the ones a HABTM relationship establishes to remove orphaned entries from the join table. Instead you should be usingActiveRecord::Base#destroy
.You will have to use raw SQL to remove the unneeded entries. If you decide to create a join model, you can iterate through entries in the join model, deleting those without an association.
Example:
连接表中的条目应该被删除,而无需您执行任何特殊操作。如果遇到奇怪的情况,您可以将
:delete_sql
选项添加到代码中来更改行为。删除连接另一侧的对象不是默认行为。The entries in the join table should be getting deleted without you doing anything special. You can add the
:delete_sql
option to your code to change the behavior if you have a weird situation. Deleting the object on the other side of the join is not a default behavior.