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

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

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 show edit and destroy all the users. I tried following the tutorials but none of them helped. I am using rails 3.0.10 and ruby 1.9.2-p290.

回答1:

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.......



回答2:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!