一个名叫Carly的用户未注册并进入主页。她注册成功后自动重定向到主仪表板页面。现在被命名为CarlyCoolness123的用户关闭浏览器去吃晚饭了。回来后,她只记得实际主页的名称coolness.com,而不是coolness.com/index-dashboard。如果该用户已登录,则希望自动将其重定向到仪表板页面。这意味着,如果用户已登录,则无法访问主页。我该怎么做?我尝试了几种方法,但由于我认为这里的人们对此有更好的理解,所以我假设这里不需要包含我的错误。
假设你已经正确地设置了Devise,并且有一个负责呈现仪表板视图的Dashboard控制器。在你的app/controllers/dashboard_controller.rb文件中执行以下操作:
class DashboardController < ApplicationController
before_filter :authenticate_user!
...
end
然后在你的 config/routes.rb 文件中添加以下内容:
resources :dashboard
authenticated :user do
root :to => "dashboard#index"
end
root :to => redirect("/users/sign_in")
如果你的仪表盘有一个索引视图,访问应用程序根目录时应该自动呈现它(如果用户已登录)。 如果用户未登录,则会重定向到设备默认的sign_in视图(如果您没有重新定义它)。root_path
时,而是重定向到不同的路径: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
虽然这是一篇旧帖子,但我遇到了类似的问题,因为我没有使用devise而是使用bcrypt,所以这就是解决方法。我在我的应用控制器中定义了current_user
和authorize
。
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
def authorize
redirect_to 'home/index' unless current_user
end
before_filter :authorize
,如果它们失败,则被引导到主页。希望这对未来的某个人有所帮助!