Search code examples
ruby-on-rails-4devise

Edit other user as admin in devise, ruby on rails


I'm using devise in my Ruby on Rails project and users have an admin-attribute:

schema.rb:

     create_table "users", force: :cascade do |t|
       .

        t.boolean  "admin",                  default: false
      end

I want, that an admin user can edit other users. I'm not the first one asking this question, but all the given answers lack clear instructions:

  1. There is an entry in the devise wiki from 2011: https://github.com/plataformatec/devise/wiki/How-To%3a-Manage-users-through-a-CRUD-interface

But I don't understand what I need to do: It mentions "devise_for :users, :path_prefix => 'my'" in the routes, but I don't have that in my routes. Then, it mentions, how I need to remove the password key of the params hash, but my users_controller is empty. No more instructions are provided.

  1. There is a stackoverflow answer to this: Devise: Allow admins to edit other users - Rails

But I don't fully understand, what needs to be done: I see, that I need to add devise_for :users, :path_prefix => 'd'to my routes, but the poster talks also about building out your forms and controller on your own, and isolating the Userscontroller. I don't understand, what he means.

  1. There is another stackoverflow answer: Rails, Devise - Admin trying to edit another user profile, own profile loaded instead

In this one, the poster uses cancan and it seems, he does have an admin class in his usercontroller, which I don't have:

class Admin::UsersController < ApplicationController
  def index
    @users = User.all
  end
end

Once again, I don't know, how the poster got there and what he did.

Is there a step-by-step guide, to let the admin-user edit other userprofiles?

You can access my code here: https://github.com/Metaphysiker/philosophica

Thanks in advance!


Solution

  • I figured it out:

    1. add a prefix in routes on devise_for :users,: :path_prefix => 'my'
    2. add this below devise_for: resources :users
    3. copy edit.html.erb from the registration from devise to users.
    4. Change <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>

    to: <%= form_for(@user) do |f| %>

    1. Add this to the usercontroller:

         def edit
           @user = User.find(params[:id])
         end
      
      
         def update
           @user = User.find(params[:id])
           if @user.update(user_params)
             redirect_to adminpanel_path
           else
             render 'edit'
           end
         end
      

    Done. (strangely, I can't put number 5 in code)