如果Pundit未获得展示操作授权,则重定向到特定视图

jam*_*es 4 model-view-controller authorization ruby-on-rails ruby-on-rails-4 pundit

我的提案控制器有以下操作:

      def show
        @proposal = Proposal.find(params[:id])
        authorize @proposal
      end
Run Code Online (Sandbox Code Playgroud)

我有以下政策:

class ProposalPolicy
  attr_reader :current_user, :proposal
Run Code Online (Sandbox Code Playgroud)

如何重定向到特定页面.如果在尝试转到显示页面时拒绝权限,请说索引提案或根页?

当我在没有正确权限的情况下导航到它时,我只会得到一个带有以下内容的rails错误页面:

not allowed to show? this<proposal OBJ ispsum lorem>
Run Code Online (Sandbox Code Playgroud)

我只是希望他们有一个简单的通知并重定向到另一个页面.什么是最好的方法呢?我在show视图中猜测某种if语句但到目前为止还没有任何工作.

  def initialize(current_user, proposal)
    @current_user = current_user
    @proposal = proposal
  end

  def show?
    @proposal.published? or @proposal.proposer == @current_user
  end
end
Run Code Online (Sandbox Code Playgroud)

trh*_*trh 10

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
Run Code Online (Sandbox Code Playgroud)

更多信息请访问:https://github.com/elabs/pundit#rescuing-a-denied-authorization-in-rails