Dynamo
Dynamo

Reputation: 77

How to delete user related data when deleting the user?

I'm working on a ROR application which uses ActiveAdmin. I want to achieve something like this - When we delete a user the devices registered by him should also get delete.

The code of batch action is as follows -

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

I want to add a command here in batch action which first delete the devices register by that user and then delete the user.

NOTE: Want to achieve this without affecting the model.

Is there any way to achieve this? Any kind of help would be greatly appreciated.

Upvotes: 0

Views: 397

Answers (3)

Cassandra S.
Cassandra S.

Reputation: 770

The best option is to specify a dependent: :destroy or dependent: :delete_all on the model. If that's not something you can do, you could theoretically achieve the same through something like this (untested):

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

Upvotes: 2

bijan rostamnejad
bijan rostamnejad

Reputation: 1

class Parent
  has_many :children, dependent: :destroy
  #or 
  has_many :children, dependent: :delete_all
end

with :destroy ==> delete the objects by calling destroy method.(it run the call backs of its children in deleting)

but :delete_all ==> All associated objects are destroyed immediately without calling callbacks.

Upvotes: 0

TheGeorgeous
TheGeorgeous

Reputation: 4061

Assuming the devices are a separate class and the dependency has been declared in the User model, you can set dependent: destroy to delete all dependent entries.

class Parent
  has_many :children, dependent: destroy
end

Upvotes: 0

Related Questions