deleting users in devise generated model

2019-08-11 08:50发布

问题:

First of all I am new to rails. I used devise gem for user authentication. Now I want to provide admin a way to delete other users. id of the user is not passing to my destroy action. Here is my code

user_controller.rb

  class UsersController < ApplicationController

  def destroy
    User.find(params[:id]).destroy
    redirect_to dashboard_path
  end

end

dashboard.html.erb

<% if current_user.admin == true %>
  <% @users = User.all %>
  <% @users.each do |user| %>
    <%= user.email %>
    | <%= link_to "delete", destroy_path, method: :delete, data: { confirm: "Are you sure"} %><br>
  <% end %>
<% end %>

回答1:

First of all, You shouldn't assign instance variables directly in your views. This is a Controller responsibility. So, in the above example, the right thing to do is something like this:

# users_controller.rb

class UsersController < ApplicationController
  def dashboard
    @users = User.all
  end

  def destroy
    User.find(params[:id]).destroy
    redirect_to dashboard_path
  end
end

And your view should look something like this:

# dashboard.html.erb

<% if current_user.admin == true %>
   <% @users.each do |user| %>
     <%= user.email %>
     | <%= link_to "delete", user, method: :delete, data: { confirm: "Are you sure"} %><br>
  <% end %>
<% end %>

And last but not least =P make sure your routes.rb have something like this:

# routes.rb

delete "/users/:id" => "users#destroy", as: :user

Of course it's just an example based on your question, but it should work like a charm =P