Rails - How To Destroy Users Created Under Devise?

后端 未结 5 1444
北海茫月
北海茫月 2020-12-15 07:13

For my application, I have user accounts that people can sign up. I use the devise gem for the setup.

I also have a users page that lists out all the u

相关标签:
5条回答
  • 2020-12-15 07:31

    At least the latest version of Devise does provide such functionality out of the box, if a Devise-backed model has :registerable included.

    class User < ApplicationRecord
      devise :database_authenticatable, :registerable
    end
    

    Somewhere in app/views/layouts/application.html.erb:

    <%= link_to 'Delete my account', user_registration_path, method: :delete if user_signed_in? %>
    
    0 讨论(0)
  • 2020-12-15 07:33

    According to devise 4.1 rake routes and views, using the following will help you delete the account once logged in as a user.

    <%= link_to "Cancel my account", registration_path(current_user), data: { confirm: "Are you sure?" }, method: :delete %>
    
    0 讨论(0)
  • 2020-12-15 07:37

    Devise doesn't provide this functionality out of the box. You have created your own destroy action, but you also have to create a custom route to that action.

    In your routes:

     match 'users/:id' => 'users#destroy', :via => :delete, :as => :admin_destroy_user
    

    And then when creating the link:

    <%= link_to "Destroy", admin_destroy_user_path(user), method: :delete, data: { confirm: "You sure?" } %>
    
    0 讨论(0)
  • 2020-12-15 07:44

    Or from rails c you can do something like this where "x" is user id.

    user = User.where(id: x)
    user.destroy(1) 
    
    0 讨论(0)
  • 2020-12-15 07:48

    I think you have in your routes.rb: resources :users

    The problem is that you are not passing the user that you want to delete when clicking:

    users/_user.html.erb

    <%= link_to "Destroy", user, method: :delete, data: { confirm: "You sure?" } %>
    

    See that in second param I added user instead of user_url.

    users_controller.rb

     def destroy
        @user = User.find(params[:id])
    
        if @user.destroy
            redirect_to root_url, notice: "User deleted."
        end
      end
    

    In controller I removed an @user.destroy. You were calling it twice.

    Hope it helps!

    0 讨论(0)
提交回复
热议问题