Admin user administration with Devise

前端 未结 2 981
终归单人心
终归单人心 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条回答
  •  Happy的楠姐
    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
    

提交回复
热议问题