删除用户时如何删除用户相关数据?
How to delete user related data when deleting the user?
我正在开发一个使用 ActiveAdmin 的 ROR 应用程序。我想实现这样的目标 - 当我们删除用户时,他注册的设备也应该被删除。
批量操作代码如下-
batch_action :destroy, :confirm => "Are you sure you want to delete these users?", do |ids|
SearchableUser.where(id: ids).destroy_all
redirect_to users_path, :notice => "Successfully destroyed users"
end
我想在批处理操作中添加一条命令,首先删除该用户注册的设备,然后再删除该用户。
注意:希望在不影响模型的情况下实现这一点。
有什么办法可以实现吗?任何形式的帮助将不胜感激。
假设设备是一个单独的class并且已经在用户模型中声明了依赖项,您可以设置dependent: destroy
删除所有依赖项。
class Parent
has_many :children, dependent: destroy
end
class Parent
has_many :children, dependent: :destroy
#or
has_many :children, dependent: :delete_all
end
with :destroy ==> 通过调用 destroy 方法删除 objects。(它 运行 其 children 在删除时的回调)
但是 :delete_all ==> 所有关联的 objects 都立即销毁而不调用回调。
最好的选择是在模型上指定 dependent: :destroy
或 dependent: :delete_all
。如果那不是你能做的事情,理论上你可以通过这样的事情(未经测试)实现同样的目标:
batch_action :destroy, :confirm => "Are you sure you want to delete these users?", do |ids|
Children.where(parent_id: ids).destroy_all
Parent.where(id: ids).destroy_all
redirect_to users_path, :notice => "Successfully destroyed users"
end
我正在开发一个使用 ActiveAdmin 的 ROR 应用程序。我想实现这样的目标 - 当我们删除用户时,他注册的设备也应该被删除。
批量操作代码如下-
batch_action :destroy, :confirm => "Are you sure you want to delete these users?", do |ids|
SearchableUser.where(id: ids).destroy_all
redirect_to users_path, :notice => "Successfully destroyed users"
end
我想在批处理操作中添加一条命令,首先删除该用户注册的设备,然后再删除该用户。
注意:希望在不影响模型的情况下实现这一点。
有什么办法可以实现吗?任何形式的帮助将不胜感激。
假设设备是一个单独的class并且已经在用户模型中声明了依赖项,您可以设置dependent: destroy
删除所有依赖项。
class Parent
has_many :children, dependent: destroy
end
class Parent
has_many :children, dependent: :destroy
#or
has_many :children, dependent: :delete_all
end
with :destroy ==> 通过调用 destroy 方法删除 objects。(它 运行 其 children 在删除时的回调)
但是 :delete_all ==> 所有关联的 objects 都立即销毁而不调用回调。
最好的选择是在模型上指定 dependent: :destroy
或 dependent: :delete_all
。如果那不是你能做的事情,理论上你可以通过这样的事情(未经测试)实现同样的目标:
batch_action :destroy, :confirm => "Are you sure you want to delete these users?", do |ids|
Children.where(parent_id: ids).destroy_all
Parent.where(id: ids).destroy_all
redirect_to users_path, :notice => "Successfully destroyed users"
end