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 del开发者_如何学Pythonete 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?
Replace 'user' by the actual user that you want to destroy, ex: if you're printing out the email as user.email, then plugin the user there et voilà
<%= 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
精彩评论