A user named Carly is not signed up and arrives at the index page. She signs up and gets automatically redirected to the main dashboard page. The user Carly which is now named CarlyCoolness123 closes her browser and goes to eat dinner. She gets on her PC again, but this time since she only remembers the actual index page called: coolness.com, and not coolness.com/index-dashboard. I want this user to be automatically redirect to the dashboard page if the user is signed in. That means that the user can't access the index page if the user is signed in. How do I do this? I've tried a couple of things, but since I assume that you people here have a lot better understanding with this than me I assume that my mistakes don't need to be included here.
This assumes that you have setup Devise correctly and you have a Dashboard controller that is responsible for rendering the dashboard view. In your app/controllers/dashboard_controller.rb do this:
class DashboardController < ApplicationController
before_filter :authenticate_user!
...
end
Then in your config/routes.rb file add the following:
resources :dashboard
authenticated :user do
root :to => "dashboard#index"
end
root :to => redirect("/users/sign_in")
If you have an index view for the dashboard, accessing the root of your app should automatically render it (if the user is signed in). If the user is not signed in, it will redirect to devise default sign_in view (if you haven't redefined it)
I prefer to use the below method, as it seems counterintuitive to me to have multiple root paths [read: "I was getting an error when I tried the other mentioned ways, so I tried something else."].
I think this works better and is actually what @MFCS was originally asking, since it doesn't make the root point somewhere else conditionally. Instead redirects to a different path when the signed in user visits the root_path
:
config/routes.rb:
root to: 'welcome#index'
app/controllers/welcome_controller.rb:
class WelcomeController < ApplicationController
def index
if user_signed_in?
redirect_to dashboard_path
end
end
end
I prefer this, since the dashboard will still have the dashboard url show up in the browser (instead of the root url), although this may not be the preference of others, and also depends on your preferred user experience.
EDIT: I made a mistake in the code, referencing the DashboardController instead of the controller of the root resource.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With