Kush
Kush

Reputation: 31

Set different route page for non admin users (attribute) (devise gem on ruby on rails)

Im currently learning ROR and have bumped into a small issue regarding different root pages depending on the user type. In my user model i have an attribute for admin which is either true or false depending on the user.

Please see my routes file below, currently all users aways go to 'houses#index', even if they have admin set as false.

I cannot see where i am going wrong in my routes file.

Is there anyway to add a condition for attribute admin on authenicated user in my routes file?

Routes.rb

Rails.application.routes.draw do
  devise_for :user
  get 'welcome/index'
  resources :houses
  resources :tenants
  resources :requests

  authenticated :user do
    root 'houses#index', as: "authenticated_root"
  end

  authenticated :user, {admin:'false'} do
    root 'requests#index', as: "authenticated_root1"
  end

  root 'welcome#index'
end

model\User.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  has_many :houses
  has_many :tenants
  has_many :requests

  def admin?
    admin
  end

end

Thanks.

Upvotes: 0

Views: 280

Answers (1)

cercxtrova
cercxtrova

Reputation: 1673

You should use after_sign_in_path_for devise's method in your application_controller.

https://github.com/plataformatec/devise/wiki/How-To:-redirect-to-a-specific-page-on-successful-sign-in

For instance:

def after_sign_in_path_for(resource)
  stored_location_for(resource) || (resource.admin? ? admin_dashboard_url : user_dashboard_url(resource))
end

(Please note that resource is like an alias for the user instance. By default it's the first devise role declared in your routes as said here: https://stackoverflow.com/a/40825885/10347572)

For all other requests, if you're not using Cancan, create a new method (pretty similar to the one above) to redirect the user according to his type (but if a user wants to access to an admin page, you should raise a 404 and not just a root redirection)

Upvotes: 1

Related Questions