简体   繁体   中英

Destroying users as an admin in Devise

I am trying to use Devise to delete users. I have a list of users each with their email and a 'delete' link next to them, only visible to me, the administrator. I want to be able to simply click the delete link to remove the user forever. The following code deletes me, the administrator!

<%= link_to "delete", user_registration_path, :method => :delete, :confirm => "You sure?" %>

I would think you need to pass the :id of the user you want to delete to some kind of 'destroy_user' method:

@user.find(params[:id]).destroy_user

But how do you do this when you have to submit a DELETE request to the user_registration_path??

------ EDIT --------

OK, I've added this method to my users controller:

def destroy
  User.find(params[:id]).destroy
  flash[:success] = "User destroyed."
  redirect_to users_path
end

So, I need to tell the users controller to invoke the destroy method when it receives a DELETE request. How do you do this in routes.rb? Currently I have:

match '/users/:id', :to => 'users#show',    :as => :user
match '/all_users', :to => 'users#index',   :as => :all_users

I need something like:

match 'delete_user', :to => 'users#destroy', :as => :destroy_user, :method => :delete

but this doesn't work. And what should go in the link?:

<%= link_to "delete", destroy_user, :method => :delete, :confirm => "You sure?" %>

To put it another way, what should you put in the routes.rb file in order to distinguish between different request types (GET, DELETE etc) to the same url?

用您要销毁的实际用户替换“用户”,例如:如果您将电子邮件打印为user.email,则将用户插入其中。

<%= link_to "delete", user_registration_path(user), :method => :delete, :confirm => "You sure?" %>

Devise doesn't provide an action to delete another user, only to delete the currently logged in user. You'd have to create your own action in one of your controllers (most likely, whichever controller has the action to display all the users) to handle deleting a user other than the currently logged in one.

Got it! Simply needed to add the :via argument in routes:

match '/users/:id', :to => 'users#show',    :as => :user,         :via => :get
match '/users/:id', :to => 'users#destroy', :as => :destroy_user, :via => :delete

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM