how to execute an action if the before_action retu

2019-04-19 18:22发布

I know that with the following code:

before_action :signed_in?, only: [:new]

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??

Here it is my signed_in? method

def signed_in?
  !@current_user.nil?
end

3条回答
神经病院院长
2楼-- · 2019-04-19 19:02

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
查看更多
疯言疯语
3楼-- · 2019-04-19 19:19
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
查看更多
倾城 Initia
4楼-- · 2019-04-19 19:20

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

查看更多
登录 后发表回答