如何使用 Devise 根据用户的角色重定向用户的主(根)路径?
我正在开发一个项目管理应用程序,在该应用程序中,我有project_managers 和客户.我正在使用 Devise 和 CanCan 进行身份验证/授权.
I'm working on a project management app, and in the app, I have project_managers and clients. I'm using Devise and CanCan for authentication/authorization.
登录后我应该在什么时候将用户重定向到他们自己的特定控制器/布局/视图?有没有办法检查 routes.rb
中的 current_user.role
并根据他们是项目经理还是客户来设置根(或重定向)?这是我可以在 Devise 的某个地方做出的改变吗?
At what point after login should I be redirecting the user to their own specific controller/layout/views? Is there a way to check for current_user.role
in routes.rb
and set the root (or redirect) based on whether or not they're a project manager or a client? Is this a change I can make in Devise somewhere?
在此先感谢您的帮助!--马克
Thanks in advance for any help! --Mark
你的 routes.rb
文件不知道用户拥有什么角色,所以你将无法使用它分配特定的根路由.
Your routes.rb
file won't have any idea what role the user has, so you won't be able to use it to assign specific root routes.
您可以做的是设置一个控制器(例如,passthrough_controller.rb
),它可以读取角色并重定向.像这样:
What you can do is set up a controller (for example, passthrough_controller.rb
) which in turn can read the role and redirect. Something like this:
# passthrough_controller.rb
class PassthroughController < ApplicationController
def index
path = case current_user.role
when 'project_manager'
some_path
when 'client'
some_other_path
else
# If you want to raise an exception or have a default root for users without roles
end
redirect_to path
end
end
# routes.rb
root :to => 'passthrough#index'
这样,所有用户都将有一个入口点,然后根据他们的角色将他们重定向到适当的控制器/操作.
This way, all users will have one point of entry, which in turn redirects them to the appropriate controller/action depending on their role.