是否可以在没有用户模型或任何身份验证的情况下在Ruby on Rails中使用会话/ cookie? [英] Can I use sessions/cookies in Ruby on Rails without having a user's model or any authentication?

查看:56
本文介绍了是否可以在没有用户模型或任何身份验证的情况下在Ruby on Rails中使用会话/ cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Rails中创建一个问答游戏,并希望创建一个会话来存储当前用户的数据,以跟踪他们正确回答的问题数量。我搜索过的所有教程都先登录一次然后生成一个会话,如果没有它,我可以这样做吗?

I am creating a quiz game in Rails and would like to create a session to store the current user's data to keep track of the number of questions they answered correctly. All of the tutorials that I've searched for makes one login first then generate a session, can I do this without it?

编辑:
实际上我想要知道在没有用户模型的情况下是否有可能?

Actually I wanted to know if this was possible without having a users model at all?

推荐答案

是。 Rails会话存储机制只是将会话ID与会话存储(默认为cookie)链接起来。

Yes. The rails session storage mechanism simply links a session id with a session storage (cookie by default).

基本上是这样的-当用户首次访问您的应用程序rails时会话标识符,它是一个很长的哈希值-该标识符由Rails存储在服务器上,并通过cookie发送给用户。

It basically works like this - when a user first visits your app rails generates a session identifier which is a long hash - the identifier is stored by rails on the server and also sent to the user in a cookie.

在对应用程序的后续请求中,rails会话中间件将查看用户cookie以获取标识符,如果有效,它将取消加密会话存储cookie并将其添加到Rails会话。缺省情况下,Rails不需要您费力就可以完成所有这些操作。

In subsequent requests to the app the rails sessions middleware will look at the users cookies for the identifier and if its valid it will unencrypt the session storage cookie and add it to the Rails session. Rails does all this by default without you having to lift a finger.

您可以将会话存储用于任意数据,只要它在浏览器施加的4k限制内在饼干上。使用Redis / Memcached等其他存储或数据库存储可以使您以降低性能的代价存储更多数据。

You can use this session storage for any arbitrary data as long as its within the 4k limit imposed by browsers on cookies. Using some other storage like Redis/Memcached or database storage lets you store more data at the cost of somewhat decreased performance.

通常会看到它与授权相关的原因是,cookie是将服务器上的用户ID与浏览器后面的当前用户链接的事实上的方式。

The reason you commonly see it connected with authorization is that cookies is kind of the defacto way to link a user id on the server with the current user sitting behind the browser.

  • Rails Guides: Sessions
  • Rails Guides: Rails On Rack if you are interested in how its implemented.

这篇关于是否可以在没有用户模型或任何身份验证的情况下在Ruby on Rails中使用会话/ cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆