gpt4 book ai didi

mysql - rails : dependent: :destroy based on multiple keys

转载 作者:行者123 更新时间:2023-11-29 10:57:36 25 4
gpt4 key购买 nike

我有一个属于用户的模型通知Notification 具有属性 user_idnotified_by_id,其中包含唯一的 User id,其中 user_id 代表正在接收通知的用户,notified_by_id 代表创建通知的用户。

用户被删除时,我想销毁它创建的通知以及它收到的通知。在我的 User 模型中,我指定了 destroy 依赖项:

has_many :notifications, dependent: :destroy  

但是,这只会破坏具有与已删除的用户匹配的user_id通知。由已删除的用户创建的通知(notified_by_id等于User.id的通知)不会被删除。

如何根据两个字段指定销毁依赖项?我应该像下面那样使用 before_destroy 吗?

before_destroy :clean_notifications

def clean_notifications
Notification.where(notified_by_id: self.id).destroy_all
end

我可以通过这种方式解决眼前的问题,但我相信有更合适的方法。非常感谢任何指导。

最佳答案

您可以在 user.rb 中再添加一行

has_many :incoming_notifications, class_name: "Notification",
foreign_key: "notified_by_id", dependent: :destroy

关于mysql - rails : dependent: :destroy based on multiple keys,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42797837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com