Rails : Adding an admin role using devise who can see all the users

前端 未结 2 1242
春和景丽
春和景丽 2021-01-21 00:33

I need to create an admin role using devise for my app. I\'ve created basic authentication using devise . I have a devise user model in my app but now i need an admin who can sh

相关标签:
2条回答
  • 2021-01-21 01:15

    I have similar requirement as yours and also don't want any user to be able to signup. All that will be taken care by Admin. Her what I've done.

    I added another devise model called Admin

    rails generate devise MODEL
    

    Disable 'Registerable' for User model so that user cannot singup by themself

    user.rb

    class User < ActiveRecord::Base
      # Include default devise modules. Others available are:
      # :token_authenticatable, :encryptable, :confirmable, :lockable, :registerable,    :timeoutable and :omniauthable
      devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable
    
      # Setup accessible (or protected) attributes for your model
      attr_accessible :email, :password, :password_confirmation, :remember_me, :first_name,  :last_name, :role, :admin
      # attr_accessible :title, :body
    end
    

    Enable CRUD for user by using sample from here: https://gist.github.com/1056194

    Finally protect protect the users controller like so

    users_controller.rb

    # Add this
    before_filter :authenticate_admin!
    

    Hope this helps.

    0 讨论(0)
  • 2021-01-21 01:16

    You just define role.rb first by creating migratioin

          rails g model role  name:string
    

    then in role.rb

          class Role
             has_one:user
          end
    

    And in user model

          class user
             belongs_to :role
          end
    

    Insert two roles into DB

       1.admin
       2.user
    

    Then check by this

        if user.role.name == "admin"  
            # can do all your logic
        else
             your logic
        end
    

    Make sure insert role_id:integer into user model

    Try it.......

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