简体   繁体   中英

Resources delete method not working with Devise

I am using devise gem for authentication. For the admin user I am trying to create a page where he will see the list of all users and will be able to delete them. Because devise does not provide action for delete I created a controller where I created destroy action.

controller:

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

The view is simple, it just lists all users and posts a delete link next to them.

<% @users.each do |user| %>
  <%= user.email %> <%= link_to 'Delete', :controller => :devise, :action => :destroy, :id => (user[:id]), method: :delete, data: { confirm: "Are you sure you want to delete this user permanently?" } %>
<% end %>

Up until this point it works - the page displays all users and the delete link too. However, when I try to delete random users it just opens them in new window instead of deleting them.

My routes are as follows:

Rails.application.routes.draw do
  devise_for :admins
  devise_for :users
  resources :devise
  resources :centres
  resources :users

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

  root 'welcome#index'
  get '/index', to: 'welcome#index' 
  get '/about', to: 'welcome#about' 
  get '/help', to: 'welcome#help'
end

I need to make the delete function work. Thank you.

This is the solution for the question I posted:

controlled:

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

view:

  <%= link_to "delete", user, method: :delete,
                                  data: { confirm: "Are you sure you want to permanently delete this user?" } %>

route:

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

As far as i know, device doesn't handle destroy action. You should create a custom controller and provide a destroy action. In my case, i create a users_controller

users_controller:

def destroy
  @user.destroy

  respond_to do |format|
    format.html { redirect_to users_url }
    format.json { head :ok }
  end
end

html.erb:

<%= link_to 'Delete', user, method: :delete, data: { confirm: 'Are you sure?' } %>

routes.rb:

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