首页 > 解决方案 > 如何在一个特定实例的应用程序控制器中覆盖rescue_from

问题描述

我有这个application_controller.rb

rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

def user_not_authorized
  redirect_back fallback_location: root_url,
                 warning: 'Not authorized'
end

但对于一种方法,我需要

def slug_available
  authorize Page
rescue Pundit::NotAuthorizedError
  render status: :unauthorized
else
  render json: { available: Page.where(slug: params[:slug]).empty? }
end

但是,rescue_from它覆盖了显式rescuein slug_available,我得到的是 302 Found 而不是 401 Unauthorized。

我原以为明确rescue会优先考虑。我怎样才能做到这一点?

标签: ruby-on-railsruby

解决方案


您可以覆盖not_authorized控制器中的声明方法并检查action_name.

protected

def not_authorized
  if action_name == 'slug_available'
    render status: :unauthorized
  else
    super
  end
end

然后,您不需要授权您的slug_avaiable操作方法

def slug_available
  render json: { available: Page.where(slug: params[:slug]).empty? }
end

基本ApplicationController方法必须是受保护的方法。


推荐阅读