如果 Pundit 未授权展示操作,则重定向到特定视图
Redirect to specific view if Pundit not authorized for show action
我对我的提案控制器执行以下操作:
def show
@proposal = Proposal.find(params[:id])
authorize @proposal
end
我有以下政策:
class ProposalPolicy
attr_reader :current_user, :proposal
如何重定向到特定页面。如果尝试转到显示页面时权限被拒绝,请说索引建议或根页面?
当我在没有正确许可的情况下导航到它时,我只得到一个 rails 错误页面,其中包含以下内容:
not allowed to show? this<proposal OBJ ispsum lorem>
我只是希望他们有一个简单的通知并重定向到另一个页面。最好的方法是什么?我猜测在显示视图中使用某种 if 语句,但到目前为止没有任何效果。
def initialize(current_user, proposal)
@current_user = current_user
@proposal = proposal
end
def show?
@proposal.published? or @proposal.proposer == @current_user
end
end
Pundit 对此有一个机制。您将在名为 user_not_authorized
的控制器中创建一个私有方法 - 在其中您将能够创建一个闪光通知并添加一个位置。
class ApplicationController < ActionController::Base
protect_from_forgery
include Pundit
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
private
def user_not_authorized
flash[:alert] = "You are not authorized to perform this action."
redirect_to(request.referrer || root_path)
end
end
这里有更多信息:https://github.com/elabs/pundit#rescuing-a-denied-authorization-in-rails
我对我的提案控制器执行以下操作:
def show
@proposal = Proposal.find(params[:id])
authorize @proposal
end
我有以下政策:
class ProposalPolicy
attr_reader :current_user, :proposal
如何重定向到特定页面。如果尝试转到显示页面时权限被拒绝,请说索引建议或根页面?
当我在没有正确许可的情况下导航到它时,我只得到一个 rails 错误页面,其中包含以下内容:
not allowed to show? this<proposal OBJ ispsum lorem>
我只是希望他们有一个简单的通知并重定向到另一个页面。最好的方法是什么?我猜测在显示视图中使用某种 if 语句,但到目前为止没有任何效果。
def initialize(current_user, proposal)
@current_user = current_user
@proposal = proposal
end
def show?
@proposal.published? or @proposal.proposer == @current_user
end
end
Pundit 对此有一个机制。您将在名为 user_not_authorized
的控制器中创建一个私有方法 - 在其中您将能够创建一个闪光通知并添加一个位置。
class ApplicationController < ActionController::Base
protect_from_forgery
include Pundit
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
private
def user_not_authorized
flash[:alert] = "You are not authorized to perform this action."
redirect_to(request.referrer || root_path)
end
end
这里有更多信息:https://github.com/elabs/pundit#rescuing-a-denied-authorization-in-rails