如何在一个特定实例中在应用程序控制器中重写raid_from

时间:2018-11-23 12:27:03

标签: ruby-on-rails ruby

我的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覆盖了rescue中的显式slug_available,我得到的是302,而不是401未经授权。

我本以为显式rescue应该优先。我该如何做到这一点?

2 个答案:

答案 0 :(得分:0)

您可以覆盖控制器中的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基本方法必须是受保护的方法。

答案 1 :(得分:0)

原来是替换

render status: :unauthorized

使用

render plain: 'Not authorized.', status: :unauthorized

解决了该问题。看起来Rails试图将当前页面呈现为401状态的HTML,直到我明确表示要呈现的内容。