设计authenticate_user重定向到新的会话路径 sessions_controller.rb application_controller.rb

问题描述

Devise authenticate_user!方法重定向到新的会话路径Users::SessionsController#new。有没有办法配置它重定向到新的用户路径?

Started GET "/" for ::1 at 2020-08-21 22:54:20 -0700
Processing by WelcomeController#index as HTML
Completed 401 Unauthorized in 2ms (ActiveRecord: 0.0ms | Allocations: 1174)


Started GET "/users/login" for ::1 at 2020-08-21 22:54:20 -0700
Processing by Users::SessionsController#new as HTML

解决方法

默认情况下,当您按下登录按钮时,它将调用会话控制器的create方法来启动用户的会话。

sessions_controller.rb

 # POST /resource/sign_in

  def create
    self.resource = warden.authenticate!(auth_options)
    set_flash_message!(:notice,:signed_in)
    sign_in(resource_name,resource)
    yield resource if block_given?
    respond_with resource,location: after_sign_in_path_for(resource)
  end

此方法的最后一行是在after_sign_in_path_for之后调用另一个方法。默认情况下,after_sign_in_path_for转到路由路径中定义的根URL。您可以在应用程序控制器中覆盖此方法。

application_controller.rb

def after_sign_in_path_for(user)
   stored_location_for(user) || new_user_url(user)
end