Repository navigation
How to: Soft delete a user when user deletes account
Morris Kimani edited this page Jul 30, 2019
·
10 revisions
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:
- Add a "deleted_at" DATETIME column
- Override
users/registrations#destroyin your routes - Override
users/registrations#destroyin the registrations controller - Update user model with a soft_delete & check if user is active on authentication
- Add a custom delete message
rails g migration AddDeletedAtColumnToUsers deleted_at:datetimerake db:migrate
devise_for :users, :controllers => { :registrations => 'users/registrations' }
- Create
app/controllers/users/registrations_controller.rbif it does not already exist- Extend the Devise registrations controller
- Override the destroy method
# 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!"