Aayush
Aayush

Reputation: 1254

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

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.

Upvotes: 3

Views: 3724

Answers (2)

Azren
Azren

Reputation: 237

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.

Upvotes: 1

Kashiftufail
Kashiftufail

Reputation: 10885

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

Upvotes: 3

Related Questions