简体   繁体   English

用户未登录时如何将用户重定向到登录页面

[英]How to redirect user to login page when user is not logged in

When user is logged in we store its user id in the session. 当用户登录时,我们将其用户ID存储在会话中。

session[:user_id] = user.id

now on all other links in our site, we want the user redirected if session[:user_id] == nil 现在在我们网站的所有其他链接上,如果session[:user_id] == nil ,我们希望用户重定向

The way I think it would be done is that it will be done in each of the methods of controller. 我认为它将完成的方式是它将在控制器的每个方法中完成。

def show_customers
   if session[:user_id] == nil
     redirect_to (:controller => "authentication", :action => "login")
   #code related to show_customers goes here
end

but this will need to be done in every method of every controller. 但这需要在每个控制器的每个方法中完成。

Is there a more sane Rails'y way to do this? 是否有更理智的Rails'y方式来做到这一点?

Use a before_filter to validate the session is valid, and if you dont want to put it in every controller, put it in your application_controller (since all controllers inherit from it). 使用before_filter验证会话是否有效,如果您不想将它放在每个控制器中,请将它放在application_controller中(因为所有控制器都从它继承)。 You can also easily exclude/restrict the actions its called for by overriding the method in your controllers. 您还可以通过覆盖控制器中的方法轻松排除/限制其所要求的操作。

使用before_filter

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

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