了解 Rails 中的新会话何时开始 [英] Knowing when a new session starts in Rails

查看:34
本文介绍了了解 Rails 中的新会话何时开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将从描述一个场景开始,我愿意接受其他方法,但我想不出任何其他方法.

I'll start by describing a scenario, I'm open to other ways of doing this but I can't think of any other ways.

我在 Rails 2 应用程序上有匿名用户.当新用户访问该站点时,我想放置一个 cookie,上面写着我已经访问了该站点 1 次"并将其记录在我们的系统中.用户离开并在一个月后回来,我阅读了这个 cookie,增加了访问次数(我来过这里 2 次")并将其记录在我们的系统中.

I have anonymous users on a Rails 2 application. When a new user comes to the site, I'd like to place a cookie saying "I've visited the site 1 time" and record this in our system. The user leaves and comes back a month later I read this cookie, increment the number of visits ("I've been here 2 times") and record this in our system.

我的计划:

新会话开始时

  • 如果用户是新用户 - 创建 cookie,记录访问
  • 如果用户正在返回 - 读取 cookie、增加值、写入 cookie、记录访问

我现在卡在新会话开始时"这一步.如果您有 .net 背景,我正在寻找相当于 ASP.NET 中的 Session_Start.我可以针对每个请求查询数据库并检查是否已经记录了特定的会话 ID,但这似乎效率低下.

Where I'm stuck right now is at the "When a new session starts" step. If you have a .net background what I'm looking for is the equivalent of Session_Start in ASP.NET. I could query the database on every request and check to see if a particular session id has already been logged, but that seems inefficient.

推荐答案

实际上这是个坏主意.Rails 将会话存储在数据库或文件系统 (tmp/sessions) 中.如果您想知道用户之前是否在该页面上,您只需不要删除会话(没有会话过期).但是随后会话的数量将增长到无穷大.

Actually it's a bad idea. Rails stores the session in the db or in the file system (tmp/sessions). If you want to know, if the user was on the page before, you just don't delete the sessions (no session expire). But then the number of sessions will grow into infinity.

如果用户使用相同的浏览器在同一台机器上返回,会话将仍然存在.在您的应用程序/会话控制器中,您可以执行以下操作:

If a user returns on the same machine with the same browser, the session will be still there. In you're application / session controller you can do:

session[:visits] ||= 0
session[:visits] += 1

但是每次点击它都会增加.因此,如果您只想计算访问次数,您还需要存储上次点击时间,如果用户离开超过半小时左右,则只需增加.

but then it will be incremented with every click. So if you want to just count the visits you need to store the last clicked time as well and just increment, if the user was away more than half an hour or so.

session[:visits] ||= 0
now = DateTime.now.to_i
session[:visits] += 1 if session[:last_click] && session[:last_click] < (now - 60*30)
session[:last_click] = DateTime.now.to_i

仍然是一个坏主意,因为如果用户在不同的浏览器或计算机上返回,计数器会重新开始.(有关会话的更多信息:http://ruby.railstutorial.org/章节/签入签出#sec:sessions)

Still a bad idea, because if the user returns on different browser or computer, the counter would start again. (More about sessions: http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec:sessions)

这篇关于了解 Rails 中的新会话何时开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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