我是 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/