如何通过在Ruby中传递块来拯救?

Rah*_*dar 1 ruby ruby-on-rails ruby-on-rails-4

我在我的authorize_user一个控制器中定义了自己的方法,如:

    def authorize_user
      if !((current_user.has_role? :admin, @operator) || (current_user.has_role? :super_admin))
        raise CanCan::AccessDenied
      end
    end
Run Code Online (Sandbox Code Playgroud)

我想从CanCan异常(或任何其他例外)中解救.我在我的应用程序中使用了Rolify.如何root_url使用自定义消息进行救援并重定向到我的应用程序?

我尝试了以下选项,但没有一个工作:

试试1:

rescue CanCan::AccessDenied do |exception|
    redirect_to root_url, :alert => exception.message
end
Run Code Online (Sandbox Code Playgroud)

在这种情况下出错: syntax error, unexpected keyword_do, expecting '('

试试2:

rescue CanCan::AccessDenied
  redirect_to root_url, :alert => "Unauthorized Access"
Run Code Online (Sandbox Code Playgroud)

在这种情况下出错: Render and/or redirect were called multiple times in this action

我该如何解决这个问题?


这是我的控制器代码:

class CabsController < ApplicationController
  before_action :set_cab, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!
  after_action :authorize_user

 # Some basic CRUD actions

 private

    def set_cab
      @cab = Cab.find(params[:id])
      @operator = Operator.find(params[:operator_id])
    end


    def cab_params
      params.require(:cab).permit(:category, :number)
    end

    def authorize_user
      if !((current_user.has_role? :admin, @operator) || (current_user.has_role? :super_admin))
        raise CanCan::AccessDenied
      end
    end
end
Run Code Online (Sandbox Code Playgroud)

Jak*_*b W 6

我想你可以试试这个rescue_from方法.

例如,你的ApplicationController,看起来像这样:

class ApplicationController < ActionController::Base
  rescue_from CanCan::AccessDenied, with: :not_authorized

  #other stuff      

  private
  def not_authorized
    redirect_to root_url, alert: "Unauthorized Access"
  end
end
Run Code Online (Sandbox Code Playgroud)

由于问题已使用更多代码进行更新,因此以下是其他信息:

一些建议:

  • :authorize_user一个before_action也好.这样,即使不允许用户执行操作,您也不必担心代码在操作中运行.
  • 您可能还需要添加与使用实例变量时相同的:only选项.:set_cab@operator
  • 最后,个人的代码风格偏好的是,我会改变的if !,以unless增加阅读的流动.