简体   繁体   中英

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?

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.

You can do the following in application controller ( application_controller.rb )

protected
def authenticate_user!
if user_signed_in?
  # navigate the user to dashboard
else
  # redirect to index
end

This method can then be invoked from other controller(s) using before_filter Example:

class SomeController < ApplicationController
  before_filter :authenticate_user!
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM