Here’s a guide to set up redirection for admins and regular users to different home pages after login in a Rails application:

1. Override after_sign_in_path_for

Override the after_sign_in_path_for method in your ApplicationController:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  def after_sign_in_path_for(resource)
    if resource.admin?
      rails_admin_path  # Redirect admin to RailsAdmin dashboard
    else
      user_home_path    # Redirect regular users to user home page
    end
  end
end

 

2. Define Routes

Ensure routes are defined in config/routes.rb:

Rails.application.routes.draw do
  mount RailsAdmin::Engine => '/admin', as: 'rails_admin'

  get 'user_home', to: 'users#home', as: 'user_home'

  devise_for :users

  root 'home#index'
end

3. Create User Home Action

Add a home action to UsersController:

class UsersController < ApplicationController
  before_action :authenticate_user!

  def home
  end
end

4. Create User Home View

Create the view for the user home page:


Welcome to your home page, <%= current_user.email %>!

Need Help With Ruby On Rails Development?

Work with our skilled Ruby on Rails developers to accelerate your project and boost its performance.

Hire Ruby on Rails Developer

Support On Demand!

Related Q&A