How-to:-Soft-delete-a-user-when-user-deletes-account.md
When a user chooses to delete their account, all of their data is destroyed by devise. It may be advantageous to keep the user data but make the user inactive and unable to log in.
This is how you can soft delete a user:
users/registrations#destroy in your routesusers/registrations#destroy in the registrations controllerdeleted_at column to Usersrails g migration AddDeletedAtColumnToUsers deleted_at:datetimerake db:migrateconfig/routes.rbdevise_for :users, :controllers => { :registrations => 'users/registrations' }
users/registrations#destroy in registrations controllerapp/controllers/users/registrations_controller.rb if it does not already exist
# app/controllers/users/registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
# DELETE /resource
def destroy
resource.soft_delete
Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)
set_flash_message :notice, :destroyed
yield resource if block_given?
respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name) }
end
end
# app/models/user.rb
# instead of deleting, indicate the user requested a delete & timestamp it
def soft_delete
update_attribute(:deleted_at, Time.current)
end
# ensure user account is active
def active_for_authentication?
super && !deleted_at
end
# provide a custom message for a deleted account
def inactive_message
!deleted_at ? super : :deleted_account
end
# config/locales/*your-filename-here*.yml
en:
devise:
failure:
deleted_account: "You've deleted your account. Thanks!"