[英]RoR: Devise enum roles, redirect after sign in based on role?
我有一個用戶 model 有兩個角色作為枚舉
enum role: [:'Standard', :'Admin']
在使用 Devise 登錄后,我正在嘗試根據用戶角色重定向到相關頁面,我在文檔中使用了推薦的方法。
在我的會話中 controller...
def create
super
sign_out :user
end
def after_sign_in_path_for(_resource)
if resource.role == "Standard"
redirect_to dashboards_path
else
redirect_to dashboards_admin_index_path
end
end
在我的 controller...
before_action :authenticate_salesperson!
before_action :set_project, only: %i[show edit update destroy]
登錄時出現此錯誤,提示渲染/重定向過多(在創建方法中突出顯示超級),我想知道為什么?
Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return"
如何解決這個問題? 泰。
如果您粘貼整個控制器會很好,但似乎在您每次訪問任一頁面之前都會調用after_sign_in_path_for
方法,這會創建一個循環並因此產生錯誤。 您可以通過在每個 if else 方法中記錄一些文本以進行仔細檢查來輕松驗證這一點。
您應該做的是將此邏輯添加到 controller 中,即像這樣的根路徑
class DashboardController < ApplicationController
before_action: :after_sign_in_path_for, only: :index
private
def after_sign_in_path_for
if current_user.standard?
redirect_to dashboards_path
else
redirect_to dashboards_admin_index_path
end
end
end
謝謝。 在我的會話 controller 中的“after_sign_in”方法中刪除“redirect_to”后,此方法有效
def after_sign_in_path_for(_resource)
if current_salesperson.standard?
dashboards_path
elsif current_salesperson.admin?
dashboards_admin_index_path
end
end
在我的用戶 model...
def admin?
role == "Admin"
end
def standard?
role == "Standard"
end
您在同一操作中重定向了太多次,這就是消息的原因:“在此操作中多次調用了渲染和/或重定向。”
只需返回路徑,刪除重定向語句! 您只能在每個操作方法中重定向一次!
問候
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.