本文介绍了会话是 Rails 中的方法还是哈希?有点糊涂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个非常简单的问题.我正在做 Michael Hartl 的 railstutorial,它谈到了使用 session 方法:

Got a really simple question. I'm doing the railstutorial by Michael Hartl and it talks about using the session method:

在 Rails 定义的 session 方法的帮助下,登录用户很简单......我们可以将 session 视为一个散列,并按如下方式分配给它:

Logging a user in is simple with the help of the session method defined by Rails... We can treat session as if it were a hash, and assign to it as follows:

session[:user_id] = user.id

它说你可以把 session 当作一个散列来对待,但我很困惑,因为它被称为 session 方法,所以实际上有什么被调用的吗?我的猜测是,通过插入会话哈希,有一个会话函数可以查看哈希以查看是否存在任何内容?我不太确定它是如何工作的.

It says you can treat session as if it were a hash, but I'm confused because it is called the session method, so is anything actually being called? My guess is that by inserting into the session hash, there is a session function that looks into the hash to see if there is anything present? I'm not really sure how it works.

推荐答案

不提Session 文档:

所有会话存储使用 cookie 来存储每个会话的唯一 ID(您必须使用 cookie,Rails 不允许您在 URL 中传递会话 ID,因为这样不太安全).

基本上,每次有人访问您的 Rails 应用时,它都会在他们的浏览器中创建一个小 cookie,可通过唯一 ID(不是用户 ID)进行识别.

Basically, each time someone visits your Rails app, it will create a small cookie in their browser, identifiable by a unique ID (not user ID).

这个 cookie 本质上是一个 Ruby 哈希,因此你可以在其中存储哈希数据:

This cookie is essentially a Ruby hash, hence why you can store hashed data inside it:

session[:your_hash] = "TEST"

这将允许您通过请求存储小数据片段(例如 user_id 或其他).

This will allow you to store small snippets of data (such as user_id or others) through requests.

Rails 有这个的主要原因归结为 HTTP 是一个 无状态协议.

The main reason Rails has this is down to HTTP being a stateless protocol.

无状态协议与有状态协议相反;它们不保留请求之间的状态,因此每次访问应用程序的新实例时,您都必须重新调用数据等.

Stateless protocols are contrary to stateful protocols; they don't retain the state between requests, thus you have to reinvoke data, etc, each time a new instance of the application is accessed.

简单地说,这意味着 Rails 是一个愚蠢"的系统——只记住你每次请求发送的数据.会话变量几十年来一直被开发人员用来提供有关用户/偏好等的基本信息,允许您针对每个请求重建"一个用户.

Simply, this translates into Rails being a "dumb" system - only remembering data you send it each request. Session variables have been used by developers for decades to provide base information about users / preferences etc, allowing you to "rebuild" a user with each request.

这就是您必须将 user_id 保存为会话的原因 - 每次您希望引用登录用户的数据时,都必须从该 id 构建> 存储在会话哈希中.

This is why you have to save the user_id as a session - each time you wish to reference a logged-in user's data, it has to be built from that id stored in the sessions hash.

这篇关于会话是 Rails 中的方法还是哈希?有点糊涂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 22:40