Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Devise set different root path per user type

I've created a devise user model. There are 2 types of user:

  • customer
  • admin

I've accomplished bij creating two 'normal' models: customer and admin. These two models are inheriting from the user model, like so:

class Customer < User

Does anyone know how I can setup a root path per type of user. I want something like this:

authenticated :customer do
  root :to => "customer/dashboard#index"
end

authenticated :admin do
  root :to => "admin/dashboard#index"
end    

UPDATE:

I've solved the problem:

root :to => "pages#home", :constraints => lambda { |request|!request.env['warden'].user}
root :to => 'customer/dashboard#index', :constraints => lambda { |request| request.env['warden'].user.type == 'customer' }
root :to => 'admin/dashboard#index', :constraints => lambda { |request| request.env['warden'].user.type == 'admin' }
like image 476
Michel Post Avatar asked Nov 06 '12 17:11

Michel Post


2 Answers

although an old question, there is no answer and it could be useful for others.

In rails 3.2 (I have never tested it with anything lower) you can do this in your routes.rb file

authenticated :admin_user do
  root :to => "admin_main#index"
end

then have your normal root route further down.

This however, doesn't seem to work in rails 4 as it gives Invalid route name, already in use: 'root' (ArgumentError)(as I have just found out and was searching for a solution when I came across this question), if I figure out a way of doing it in rails 4 I will update my answer

Edit:

Ok so for rails 4 the fix is pretty simple but not so apparent right off the bat. all you need to do is make the second root route a named route by adding an as: like this:

authenticated :admin_user do
  root :to => "admin_main#index", as: :admin_root
end

this is documented here but note that it seems like only a temporary fix and so is subject to change again in the future

like image 146
DazBaldwin Avatar answered Oct 27 '22 13:10

DazBaldwin


What you could do is have a single root path, say home#index and in the corresponding controller action perform a redirect depending on their user type.

For instance:

def index
  if signed_in?
    if current_user.is_a_customer?
      #redirect to customer root
    elsif current_user.is_a_admin?
      #redirect to admin root
    end
  end
end
like image 21
Noz Avatar answered Oct 27 '22 11:10

Noz