Skip to content

How to Setup Multiple Devise User Models

Wajid Kagzi edited this page May 26, 2016 · 1 revision

One of the best features of Devise is its ability to provide a complete set of functionality for multiple types of Users. For example, say we want to build an ecommerce app where there will be three types of users: Shoppers, Retailers and Admins.

Now we could combine Devise with some role ability gem so that we have a database attribute that checks which type of user is signing in. There are advantages to this approach.

However, creating a single devise model for each type gives your application more flexibility and feels natural. By doing this we are able to have sign up, log in, forget password, mailers, confirmation instructions all specific to that type of user with the namespace included. A technical issue with this type of setup, however, is that a signed in devise user will be able to access sign in and login pages of another devise user. This is definitely not a desired result.

As a solution, a simple concern can be implemented. Here it is called, Accessible.

module Accessible
  extend ActiveSupport::Concern

  protected

  def check_user
    flash.clear
    if current_admin
      redirect_to(rails_admin.dashboard_path) && return
    elsif current_shopper
      redirect_to(authenticated_shopper_root_path) && return
    elsif current_retailer
     redirect_to(authenticated_retailer_root_path) && return
    end
  end
end

Here we are redirecting and returning any user that is trying to access pages that are not specific to the type of user they are. Including this concern in your Sessions and Registrations Controller while performing this check as a before_action on your new methods is one simple way to setup multiple users for devise.

Clone this wiki locally