haseeb haseeb - 6 months ago 21
Ruby Question

Rails Devise - Define separate root paths for signed in user and anonymous user

I want the

root_path
of a signed_in user to be
dashboard
and users that are not signed in user to be
index
.

I am using Devise and I know there is a helper
user_signed_in?
but I dont understand how to use it for this purpose.

How do I make this work?

Answer

You can use this:

unauthenticated :user do
  root :to => 'main#index'
end

authenticated :user do
  # Rails 3 syntax
  # root :to => "main#dashboard"   
  # Rails 4 requires the 'as' option to give it a unique name
  root :to => "main#dashboard", :as => "authenticated_root"
end

This is the mechanism provided by Devise for re-rooting authenticated users.

The root :to => 'main#index' line is the standard line that Rails places in your config/routes.rb when the application is first created. You can wrap it in the unauthenticated :user do .. end block to make certain that it applies to users that are not logged in.

This gives definitive root routing for all users, based on whether they're logged in.

Comments