新手问题 如何优雅地通过 before_action 来跳过 action 指定代码的执行?

wfwdex · 2016年09月08日 · 最后由 wfwdex 回复于 2016年09月19日 · 2674 次阅读

action 里有部分代码需要通过判断一个来自 ApplicationController 的成员是否为真来执行。

每个 action 都要加代码这样判断,有些麻烦

有没有办法通过设置 before_action 来判断一下,如果为否,直接跳到后面的渲染,而不执行那段代码?

考虑整理业务逻辑

Before action 有调用 render 或 redirect,后续的 action 就会跳过。

return render: / redirect 如果不 return 可能会报错。

或者直接 rack 层作处理也可以。

#2 楼 @Rei 好的,多谢

#3 楼 @icepoint1999 http://guides.rubyonrails.org/action_controller_overview.html#filters

If a "before" filter renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter, they are also cancelled.

本来就是设计的拦截器

#5 楼 @zhang_soledad 谢谢,明白了,就是说后面如果还有 filter,也会被拦截。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号