关闭浏览器时会话未被破坏 – RailsTutorial.org

通过Michael Hartl的railstutorial.org,我在第8章(特别是8.2.3)。 当前的问题是实现一个会话以保持用户在多个视图中登录,但本节中实现的function应该是一个临时会话,当浏览器窗口关闭时该会话过期(将用户注销)。 以下是教科书中的陈述,表明:

如果您完全退出浏览器,您还应该能够validation应用程序是否忘记了您的登录状态,要求您再次登录以查看上述更改。

我已在Google Chrome和Firefox上测试了此function – 我成功登录,导航到多个页面(以确保我的会话持续超出log_in重定向)然后关闭浏览器 – 但是当我重新加载Web应用程序时,我仍然登录。我已经完全按照文本中的内容复制了所有代码,但无济于事。 作为参考,这是我的sessions_helper.rb文件:

 module SessionsHelper # Logs in the given user. def log_in(user) session[:user_id] = user.id end # Returns the current logged-in user (if any). def current_user @current_user ||= User.find_by(id: session[:user_id]) end # Returns true if the user is logged in, false otherwise. def logged_in? !current_user.nil? end end 

这里是我的sessions_controller.rb文件( destroy动作尚未实现,因为我没有在给出Logout按钮的任何function的文本中指出这一点):

 class SessionsController < ApplicationController def new end def create user = User.find_by(email: params[:session][:email].downcase) if user && user.authenticate(params[:session][:password]) # Log the user in and redirect to the user's show page. log_in user redirect_to user else flash.now[:danger] = 'Invalid email/password combination' render 'new' end end def destroy end 

结束

注意:在您的答案中,请不要建议添加替代代码或更改现有代码(除非您发现我发布的代码有误)。 教科书假定这是工作代码,并且不需要对其进行任何改动以使其正常运行。

请检查config/initializers/session_store.rb文件。 应该有类似的东西

 Rails.application.config.session_store :cookie_store, key: '_app_session' 

您必须将带有nil值的expire_after键添加到选项中:

 Rails.application.config.session_store :cookie_store, key: '_app_session', expire_after: nil 

应用此更改后,会话将在用户关闭浏览器时到期。 您可以在此处阅读有关cookie过期的更多信息

我知道我迟到了好七个月,但我有同样的问题,经过一些额外的谷歌搜索,发现它在两年前在这里被回答了 。

问题是浏览器设置,我想大多数人都会使用这些设置:“当Firefox启动时,从上次显示我的窗口和选项卡”或“启动时,继续从中断处继续”。 这个问题现在在教程( 第8章,注1 )中作为脚注提到,但作者最好说的是

…当然Rails无法控制这种行为。