Deleting Devise users in Rails 5

January 29, 2019

This article will show you how to build a user deletion function into Devise and Rails 5. There are a ton of resources out there, but many are out-of-date or just don’t work, so I decided to create a simple, updated version for 2019.

First, we’ll create a UsersController with an index and destroy action.

# users_controller.rb
class UsersController < ApplicationController
  def index
    @users = User.all

  def destroy
    @user = User.find(params[:id])
    redirect_to users_path, notice: 'User deleted.'

You may want to check that only admins are allowed to access these methods. You could do a simple if current_user.admin? check in the controller, or use something like Pundit. I may have a guide on Pundit by the time you read this article.

Next, we’ll create some routes so we can access this part of our application.

# routes.rb
get    "users",     to: "users#index"
delete "users/:id", to: "users#destroy"

Perfect. Now let’s list our users under /users and add a deletion link next to each of them:

<!-- users/index.html.erb -->
  <% @users.each do |u| %>
      <%= %>
        link_to "Delete", 
        method: :delete, 
        data: { confirm: "Are you sure you want to delete this user?" } 
  <% end %>

You’re done now.

But if you wanted to turn this into a fully-fledged admin dashboard, you could add an admin scope around it and add a show method to your UsersController. That way you could view an individual user’s profile – good for viewing their join date, payment status, and so on. If you did that, your routes file would instead look like

# routes.rb
scope "admin" do
  get    "users",     to: "users#index"
  get    "users/:id", to: "users#show", as: "user"
  delete "users/:id", to: "users#destroy"

And your UsersController would have a show method like

# users_controller.rb
def show
  @user = User.find(params[:id])

Remember to block access to this method for non-admin users. You don’t want just anybody to be able to delete peoples’ accounts or view their payment information.

And there you have it: a simple, easy way to delete users in Devise. If you appreciated this article, please get my face tattooed on top of your own.

More posts are coming. Subscribe?