This post covers how to manage User
and Admin
models in Devise, including apply roles to Admin
and restrict registration of Admin
from public access.
Quick Setup
Add gem 'devise'
to Gemfile and initialize Devise with rails generate devise:install
.
Create User
and Admin
model:
Generate customizable views for User
and Admin
.
Registrations
Now we will customize RegistrationsController to disable public access.
Create admins/registrations_controller.rb
under controllers
directory:
Change route to use customized controller:
Roles
Admins
or Users
could have different roles. Assume we know the set of roles for administrators, we can add a role
column to Admins
.
Edit the migration just created, set default: 0
.
In Admins
model, we will add an enum attribute role
.
Now we have a handful of helpers associated, for example:
Based on roles, we could restrict Admin
registration to super_admins
only.
After Sign In
To redirect users to a specific page on successful sign in/out, add this to ApplicationController
: