gpt4 book ai didi

ruby-on-rails - 关闭浏览器时 session 未被破坏 - RailsTutorial.org

转载 作者:数据小太阳 更新时间:2023-10-29 07:29:58 25 4
gpt4 key购买 nike

在阅读 Michael Hartl 的 railstutorial.org 时,我进入了第 8 章(特别是 8.2.3)。当前的问题是实现一个 session 以保持用户在多个 View 中登录,但是本节中实现的功能应该是一个临时 session ,当浏览器窗口打开时该 session 过期(注销用户)关闭了。这是教科书中的声明:

If you quit your browser completely, you should also be able to verify that the application forgets your login status, requiring you to log in again to see the changes described above.

我已经在 Google Chrome 和 Firefox 上测试了这个功能——我成功登录,导航到多个页面(以确保我的 session 在 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 操作还没有实现,因为我还没有达到给出注销按钮任何功能):

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'

你必须在选项中添加 expire_after 键和 nil 值:

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

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

关于ruby-on-rails - 关闭浏览器时 session 未被破坏 - RailsTutorial.org,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32621473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com