Rails: Devise:根据角色登录后重定向

42

在使用Devise签到后,是否可以根据角色将用户重定向到不同的页面?它似乎只会重定向到routes.rb中定义的root :to => ...页面。

7个回答

48

没错。如果您查看Devise本身的Registrations Controller,您可以看到其中的所有不同方法,然后可以随意覆盖其中任何一个。 - janders223
1
@janders223,你如何获取Devise的注册控制器访问权限? - Joel
我没有运气 :( - Frank Fang
我相信这是在 after_sign_in_path_for 之后。 - Ricky Panzer

35

您可以简单地将此方法添加到您的应用程序控制器中:

def after_sign_in_path_for(resource)
  user_path(current_user) # your path
end

谢谢,我一直在尝试找出如何在初始登录时重定向用户到新闻页面。之后,主页功能将返回正常。这是我最终用于我的代码的内容:def after_sign_in_path_for(resource) if current_user.role == 'admin' start_path else news_path end end谢谢! - Scott Milella

11

Devise提供了一个辅助方法after_sign_in_path_for,可以用于覆盖默认的Devise登录/登录后路由到根路径的设置。

要在登录后重定向到另一个路径,只需将此方法添加到您的应用程序控制器中即可。

#class ApplicationController < ActionController::Base

def after_sign_in_path_for(resource)
  users_path
end

users_path 是您希望将其重定向的路径, User 是对应于 Devise 模型的模型名称。

注意: 如果您在 Devise 中使用了 Admin 作为您的模型名称,则它将是

#class ApplicationController < ActionController::Base

def after_sign_in_path_for(resource)
  admins_path
end

另外,如果您为Devise生成了控制器,则可以在sessions控制器中定义此内容。例如,如果您的Devise模型是Admin,则可以在app/controllers/admins/sessions_controller.rb文件中定义路由到dashboard_index_path

# app/controllers/admins/sessions_controller.rb'

def after_sign_in_path_for(resource)
  dashboard_index_path
end

并且在注册控制器 - app/controllers/admins/registrations_controller.rb文件中:

# app/controllers/admins/registrations_controller.rb

def after_sign_up_path_for(resource)
  dashboard_index_path
end

就这些了。

希望这对你有所帮助。


5
您可以在应用程序控制器或任何需要执行操作的控制器中使用以下代码:
def after_sign_in_path_for(resource)
    users_path
end

3
我使用了示例1:

https://github.com/heartcombo/devise/wiki/How-To:-Redirect-to-a-specific-page-on-successful-sign-in,-sign-up,-or-sign-out

。该链接介绍了如何在成功登录、注册或退出时重定向到特定页面的方法。
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  before_action :authenticate_user!

  protected

  def after_sign_in_path_for(resource)
    current_user.is_a?(Admin) ? admin_tests_path : (stored_location_for(resource) || root_path)
  end
end

1

在 @Asnad Atta 提供的答案基础上进行扩展:

这是我最终使用的内容。

def after_sign_in_path_for(resource)
    if current_user.role == 'admin'
      start_path
    else
      news_path
    end
  end

我希望每个登录的用户都能首先进入新闻页面。 完成初始登录后,导航栏中的主页会跳转到 start_path(这是我在应用程序中称之为它的名称)。start_path 也在我的 root 中:

这个神奇的 after_sign_in_path_for(resource) 仅在初始登录时覆盖 root to: 路径。

这正是我想要的。

我希望这能帮助节省其他人的时间。 Scott


-3

2
这个问题询问的是在登录后重定向,而这个链接讨论的是更改登录和注销本身的路由(即创建和销毁会话)。 - davetapley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接