我的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
应该优先。我该如何做到这一点?
答案 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,直到我明确表示要呈现的内容。