如果 before_action 返回 false,如何执行操作 [英] how to execute an action if the before_action returns false

查看:22
本文介绍了如果 before_action 返回 false,如何执行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道使用以下代码:

before_action :signed_in?, only: [:new]

如果 signed_in? 返回 true,则操作 new 将被执行,但如果我希望 new 操作在 signed_in? 返回 false 我该怎么办?我是否必须创建一个新方法,例如 not_signed_in??

the action new will be executed if the signed_in? returns true, but instead if I want the new action to be executed when signed_in? returns false what do I have to do? Do I have to create a new method called, for instance, not_signed_in??

这是我的signed_in?方法

def signed_in?
  !@current_user.nil?
end

推荐答案

before_action 并不像您想象的那样工作 - 如果回调返回 false,它不会阻止操作的执行.我会以稍微不同的方式解决您的问题,例如:

before_action doesn't work as you think - it doesn't prevent action to be executed if callback returns false. I would solve your problem in a little bit different manner, for example:

before_action :redirect_to_root, :if => :signed_in?, :only => :new

# ...
private
def redirect_to_root
  redirect_to root_path
end

这篇关于如果 before_action 返回 false,如何执行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆