关闭浏览器时会话未销毁 - RailsTutorial.org

M. *_*ton 8 ruby session login ruby-on-rails railstutorial.org

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

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

我已经在 Google Chrome 和 Firefox 上测试了这个功能——我成功登录,导航到多个页面(以确保我的会话在 log_in 重定向之后仍然存在),然后关闭浏览器——但是当我重新加载网络应用程序时,我仍然登录。我已经完全按照文本中的描述复制了所有代码,但无济于事。作为参考,这是我的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
Run Code Online (Sandbox Code Playgroud)

这是我的sessions_controller.rb文件(该destroy操作尚未实施,因为我还没有在文本中说明为“注销”按钮提供任何功能):

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
Run Code Online (Sandbox Code Playgroud)

结尾

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

int*_*ale 6

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

Rails.application.config.session_store :cookie_store, key: '_app_session'
Run Code Online (Sandbox Code Playgroud)

您必须将expire_afternil值的键添加到选项中:

Rails.application.config.session_store :cookie_store, key: '_app_session', expire_after: nil
Run Code Online (Sandbox Code Playgroud)

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