0

this is my before_action in controller

before_action :redirect_to_home, unless: :logged_in?, only: %i[destroy]
before_action :redirect_to_home, if: :logged_in?, only: %i[new create]

My purpose is redirect to home when call new and create action for authenticated user and destroy for unauthenticated user

this is my redirect_to_home callback

def redirect_to_home
  redirect_to root_path
end

this is my logged_in? method

def logged_in?
  p 'HELLO FROM LOGGED_IN'
  session[:user_id].present?
end

when I ran the destroy test spec nothing printed out to the console but when I swap the line and run the destroy test spec again everything looks fine but new and create test spec are broken.

Do you guys have any ideas?

Thanks

Gut
  • 13
  • 2

2 Answers2

4

Ref this

Calling the same filter multiple times with different options will not work,
since the last filter definition will overwrite the previous ones.

You can do following

before_action :redirect_to_home, only: %i[new create destroy]

And in controller

def redirect_to_home
  if logged_in?
    redirect_to root_path
  else
    redirect_to destroy_path #You have to use actual destroy path here.
  end
end
Salil
  • 46,566
  • 21
  • 122
  • 156
0

before_action doesn't prevent action to be executed if callback returns false.

You can make another method:

def ensure_user_is_logged_in
  unless logged_in?
    redirect_to_home
end

Then you can use it before_action like this:

before_action :ensure_user_is_logged_in, only: %i[new, create]

It will redirect to home if the user is not logged in.

You can refer to this for more info: how to execute an action if the before_action returns false

Anas Ansari
  • 143
  • 2
  • 10