简体   繁体   English

如果用户未登录,则重定向到索引

[英]Redirect to Index if user is not logged in

I have this in my application_controller.rb: 我的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: 我在正文开始后立即将其添加到application.html.erb(页面布局)中:

<% 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? 我是否必须在某处定义一些内容才能在布局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 将此方法添加到application_helper.rb或使其成为辅助方法,如果要将其保留在application_controller.rb ,请删除private并添加以下行

helper_method :require_user_signed_in

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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