我希望已登录用户的root_path
为dashboard
,未登录用户的用户为index
。
我正在使用Devise,我知道有一个助手user_signed_in?
,但我不知道如何将其用于此目的。
我该如何做到这一点?
您可以使用这个:
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
这是Devise提供的机制,用于重新为经过身份验证的用户扎根。
root :to => 'main#index'
行是首次创建应用程序时Rails放置在config/routes.rb
中的标准行。您可以将它包装在unauthenticated :user do .. end
块中,以确保它适用于未登录的用户
这为所有用户提供了基于他们是否登录的最终根路由
您可以在应用程序控制器(application_controller.rb
)中执行以下操作
protected
def authenticate_user!
if user_signed_in?
# navigate the user to dashboard
else
# redirect to index
end
然后可以使用before_filter
从其他控制器调用此方法示例:
class SomeController < ApplicationController
before_filter :authenticate_user!
end