简体   繁体   中英

Redirect to Index if user is not logged in

I have this in my application_controller.rb:

private

  def require_user_signed_in
    unless user_signed_in?

      # If the user came from a page, we can send them back.  Otherwise, send
      # them to the root path.
      if request.env['HTTP_REFERER']
        fallback_redirect = :back
      elsif defined?(root_path)
        fallback_redirect = root_path
      else
        fallback_redirect = "/"
      end

      redirect_to fallback_redirect, flash: {error: "You must be signed in to view this page."}
    end
  end

And I added this in my application.html.erb (the layout for the page) right after the start of the body:

<% require_user_signed_in %>

My question is how why is it not working? I am getting an undefined local variable or method error. Am I not calling the method correctly? Do I have to define something somewhere for it to be usable in the layout erb?

Thank you.

Add this method to application_helper.rb instead or make it a helper method, if you want to keep it in application_controller.rb , remove private and add the following line

helper_method :require_user_signed_in

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM