'route root to different controller if user is logged in

We're using devise and are able to check if a logged in user is an admin in routes.rb so only admins can access example.com/sidekiq

authenticate :user, ->(user) { user.admin? } do
  mount Sidekiq::Web, at: '/sidekiq'
end

Is is possible to do something similar and point root to a different controller depending on whether a user is logged in or not like this pseudocode below?

if authenticate :user
  root "dashboard#main"
else
  root "pages#landing"
end


Solution 1:[1]

authenticated(:user) do
  root "dashboard#main"
end

unauthenticated(:user) do
  root "pages#landing"
end

Using unauthenticated here is really optional. You could just define it as:

authenticated(:user) do
  root "dashboard#main"
end
root "pages#landing"

And take advantage of the fact that routes have priority in the order they are defined. But it does let you swap the order if you want to.

The difference between authenticate and authenticated is that the former causes a authentication check and Warden will throw if the user is not authenticated so you get a redirect to the sign in page. authenticated will just not run the block if the user is not signed in.

See:

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 max