Masatoshi Nishiguchi
Software Engineer

Rails Devise scoped views

rails devise

If you have more than one Devise model in your application (such as User and Admin), by default Devise uses the same views for all models. But Devise offers an easy way to customize views.

Enable scoped views

Set config.scoped_views = true inside the config/initializers/devise.rb file.

/config/initializers/devise.rb

config.scoped_views = true

Create devise models (e.g., user, admin)

$ rails g devise user
$ rails g devise admin

Configure devise modules to be included in each devise model

class Admin < ApplicationRecord
  devise :database_authenticatable, :trackable, :validatable
  ...
end
class User < ApplicationRecord
  devise :database_authenticatable, :registerable, :recoverable, :rememberable,
         :trackable, :validatable, :confirmable, :omniauthable
  ...
end

Create devise controllers

$ rails g devise:controllers users
$ rails g devise:controllers admins

Configure namespaced devise routes

Rails.application.routes.draw do
  devise_for :admins, controllers: {
    sessions:           "admins/sessions"
  }
  devise_for :users, controllers: {
    sessions:           "users/sessions",
    passwords:          "users/passwords",
    registrations:      "users/registrations",
    confirmations:      "users/confirmations",
    omniauth_callbacks: "users/omniauth_callbacks"
  }
  ...
end

Delete unnecessary devise files


References