Admin user administration with Devise

前端 未结 2 950
终归单人心
终归单人心 2021-02-04 13:50

I am trying out Devise for the first time. One of the things that I wanted to do is provide an interface for Admin users to create, find and edit users. Here\'s where I may have

相关标签:
2条回答
  • 2021-02-04 14:07

    This is how I manage users in one of my apps. I have only one User class generated with

    rails g devise User
    

    to which I added a role column with this migration:

    class AddRoleToUser < ActiveRecord::Migration
      def change
        add_column :users, :role, :string, :default => "client"
      end
    end
    

    and my User model:

    class User < ActiveRecord::Base
      # Include default devise modules. Others available are:
      # :token_authenticatable, :confirmable, :lockable and :timeoutable
      devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable
    
      # Setup accessible (or protected) attributes for your model
      attr_accessible :email, :password, :password_confirmation, :remember_me
    
      def admin?
        self.role == "admin"
      end
    end
    

    Then to create new users all you would have to do is provide a custom method in a controller (maybe even subclass Devise::RegistrationsController) like this:

    # some_controller.rb
    def custom_create_user
      if current_user.admin?
        User.create(:email => params[:email], password => params[:password])
        redirect_to(some_path, :notice => 'sucessfully updated user.')
      else
        redirect_to(some_other_path, :notice => 'You are not authorized to do this.')
      end
    end
    
    0 讨论(0)
  • 2021-02-04 14:08

    Thank you very much for the help. This is essentially exactly what I am doing. I discovered a clue that helped me solve the problem of the user's session being cleared when they edit their own record in this wiki:

    https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-edit-their-account-without-providing-a-password

    This is the line I needed:

    sign_in resource_name, resource, :bypass => true
    

    This method is located in Devise::Controllers::Helpers so I did this in my controller.

    class PeopleController < ApplicationController
       include Devise::Controllers::Helpers
    

    Then in my update method I call it only if the current_user.id equals the id that is being edited:

    def update
      @person = User.find(params[:id])
      if @person.update_attributes(params[:user])
        sign_in @person, :bypass => true if current_user.id == @person.id
        redirect_to  person_path(@person), :notice  => "Successfully updated user."
      else
        render :action => 'edit'
      end
    end
    

    Now if the current user edits their own record, the session is restored after it is saved.

    Thanks again for your responses.

    0 讨论(0)
提交回复
热议问题