【问题标题】:Edit new user session path when accessing protected page访问受保护页面时编辑新用户会话路径
【发布时间】:2014-08-24 21:56:29
【问题描述】:

当用户登录时,用户会被重定向到 /dashboard/index。所以 /dashboard/index 受保护:

class DashboardController < ApplicationController
  before_action :authenticate_user!
  def index
  end
end

现在,如果有人尝试在未登录的情况下直接访问 /dashboard/index。用户将被重定向到 /users/sign_in,并显示闪烁消息“您需要先登录或注册才能继续。”

我怎样才能让用户重定向到 root_path(并且仍然得到那个 flash 消息)?

我尝试过不成功:

class ApplicationController < ActionController::Base
  def new_user_session_path(resource)
    root_path
  end 

【问题讨论】:

标签: ruby-on-rails devise


【解决方案1】:

Devise wiki 上有一个 recipe/workaround 说明如何执行此操作。

不过,使用自定义身份验证器可能更容易。 除了使用 Devise 附带的 before_action :authenticate_user! 之外,您还可以添加自己的身份验证器来重定向到其他地方。

class ApplicationController

  protected

  def user_auth
    unless user_signed_in?
      # Set flash message
      redirect_to root_path
    end
  end
end

然后告诉你的控制器使用user_auth而不是authenticate_user!

【讨论】:

  • 必须将 def user_auth 替换为 def authenticate_user!它工作得很好!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-19
  • 1970-01-01
相关资源
最近更新 更多