ruby-on-rails - 如何在一个特定实例的应用程序控制器中覆盖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
它覆盖了显式rescue
in slug_available
,我得到的是 302 Found 而不是 401 Unauthorized。
我原以为明确rescue
会优先考虑。我怎样才能做到这一点?
解决方案
您可以覆盖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
方法必须是受保护的方法。
推荐阅读
- php - password_verify 始终返回 false
- python - 如何返回列表中匹配的所有匹配项?
- r - 使用混合悬停和单击在闪亮的应用程序中创建横断线
- javascript - 当页脚出现时重新定位滚动到顶部按钮(所以它永远不会重叠)
- python - 绘制独立于过滤器的 DataFrame 的一部分
- python - python 字典,读取文件行,添加到 dict()
- python - Get text from a tag name in python selenium
- react-native - 如何调用被 onPress 方法吸引的组件?
- c# - 'EmployeeDBEntities' 可以在 C# 类库项目的应用程序配置文件中找到
- google-apps-script - 如何从谷歌表格下载PNG图表