Rails 5.2
我有两个设计模型User, Worker
用户和工作人员具有各自的设计生成视图
我为应用程序控制器配置了after_sign_in_path_for(resource)
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
# redirect after sign-in
def after_sign_in_path_for(resource)
case resource
when User
resource.update_attribute(:active, true)
dashboard_path(current_user.id)
when Worker
faq_path
end
end
def after_sign_out_path_for(resource)
# request.referer
root_path
end
end
但是,无论配置如何,登录时都会将用户重定向到root_path。
有什么我想念的吗?
答案 0 :(得分:1)
在您的路线中,您可以执行以下操作
devise_for :users, controllers: {
sessions: 'users/sessions',
}
devise_for :workers, controllers: {
sessions: 'workers/sessions',
registrations: 'workers/registrations'
}
然后您可以在/app/controllers/users/sessions_controller.rb-/app/controllers/workers/sessions_controllers.rb等文件中创建相应的文件,具体取决于您在route.rb文件中的描述。
然后,在那些文件中,您可以像这样实现自定义方法:
class Users::SessionsController < Devise::SessionsController
# before_action :configure_sign_in_params, only: [:create]
# GET /resource/sign_in
# def new
# super
# end
# POST /resource/sign_in
# def create
# super
# end
# DELETE /resource/sign_out
# def destroy
# super
# end
def after_sign_in_path_for(resource)
super(resource)
users_root_path # or whatever path you want here
end
# protected
# If you have extra params to permit, append them to the sanitizer.
# def configure_sign_in_params
# devise_parameter_sanitizer.permit(:sign_in, keys: [:attribute])
# end
end
对于每个资源而言,这都是一种更清洁的解决方案,而不是比较类,您可以自由地为特定资源自定义/覆盖其中的任何方法,而无需使代码复杂化。
我希望这会有所帮助。