gpt4 book ai didi

mysql - rails : Delete user and user associated data in all associated models

转载 作者:行者123 更新时间:2023-11-29 10:22:55 26 4
gpt4 key购买 nike

我是 Ruby ON Rails 新手,我的应用有 3 个模型

class User < ActiveRecord::Base
has_one :user_hobby
has_one :user_interest
end

class User_hobby < ActiveRecord::Base
belongs_to :User
end

class User_interest < ActiveRecord::Base
belongs_to :User

end

我想从模型和关联数据中删除特定用户的所有记录和关联数据。

我尝试过:

@user = User.joins(:User_details,:User_record).where(user_id:'user_id')
@user.destroy

但不工作,我想不使用dependent: :destroy仅来自 SQL

最佳答案

简单地说,在使用模型中的任何关联时使用依赖

你可以这样做:

class User < ActiveRecord::Base
has_one :user_hobby, dependent: :destroy # destroys the associated user_hobby
has_one :user_interest, dependent: :destroy # destroys the associated user_interest
end

要了解更多信息,请参阅此 link

依赖

  • 控制关联对象在其所有者被销毁时发生的情况:

  • :destroy 导致关联的对象也被销毁

  • :delete 导致关联对象直接从数据库中删除(因此回调不会执行)

  • :nullify 导致外键设置为 NULL。回调不会被执行。

  • :restrict_with_exception 如果存在关联记录,则会引发异常

  • :restrict_with_error 如果存在关联对象,则会导致向所有者添加错误

关于mysql - rails : Delete user and user associated data in all associated models,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48907858/

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