Ruby-on-rails 如果 before_action 返回 false 如何执行操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20120485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:03:30  来源:igfitidea点击:

how to execute an action if the before_action returns false

ruby-on-railscallbackactioncontroller

提问by zer0uno

I know that with the following code:

我知道使用以下代码:

before_action :signed_in?, only: [:new]

before_action :signed_in?, only: [:new]

the action newwill be executed if the signed_in?returns true, but instead if I want the newaction 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??

new如果signed_in?返回 true,则将执行该操作,但是如果我希望newsigned_in?返回 false时执行该操作,我必须做什么?例如,我是否必须创建一个名为 的新方法not_signed_in?

Here it is my signed_in?method

这是我的signed_in?方法

def signed_in?
  !@current_user.nil?
end

回答by Marek Lipka

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 不像您想的那样工作 - 如果回调返回,它不会阻止执行操作false。我会以稍微不同的方式解决您的问题,例如:

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

# ...
private
def redirect_to_root
  redirect_to root_path
end

回答by rene paulokat

before_action :new, unless: -> { signed_in? }

alltough i think its better to redirect in the action which was called.

虽然我认为最好在被调用的动作中重定向。

def your_action_called
  redirect_to :new unless signed_in?
  [...code ...]
end

回答by Konstantin Plyusnin

If you want to cover all other methods with
before_action :signed_in?
except new action, you'b better to use :exceptinstead of :only
like this:
before_action :signed_in?, except: :new

如果你想用
before_action :signed_in?
除了 new action来覆盖所有其他方法,你最好使用:except而不是:only
这样:
before_action :signed_in?, except: :new