Rails 4 session.id偶尔无 [英] Rails 4 session.id occasionally nil
问题描述
我在Heroku上运行一个简单的网站,当我运行应用程序时,我注意到一些奇怪的事情。看来,当我的用户登录到我的数据库时,大约50-60%的用户报告了一个无session_id。
我使用active_record_store作为会话处理程序,Postgres作为我的数据库服务器。我使用cookie_store得到了类似的结果,所以我不确定我做错了什么。我唯一的猜测是用户提出的第一个请求,该ID可能尚未填充。会话表有正确的条目数,但我的跟踪表没有。
示例代码
class CaptionController< ApplicationController
$ b $ def index
$ b @image = Image.order(RANDOM())。first
Tracking.log(session.id,Tracking :: VIEW_CAPTION_ON_IMAGE ,@ image.id)
end
以上代码的结果为50 %的时候,会话在它登录的表中为零。
我找到了答案,它看起来像Rails如果有需要存储的内容,只需创建一个会话就可以提高效率。因此,访问session.id而不存储某些内容不会返回一致的结果。
您需要强制通过在其中存储内容来创建会话。
TLDR:在您访问会话ID之前将其添加到某处。
session [:foo] =bar
来源: http://www.gani.com.au/2013/08/force-session-creation-in-rails/
I'm running a simple website on Heroku and I'm noticing something strange occurring when I'm running the app. It appears that approximately 50-60% of my users are reporting a nil session_id when it gets logged in my database.
I'm using active_record_store for my session handler and Postgres as my db server. I've gotten similar results using the cookie_store, so i'm not sure what i'm doing wrong. The only guess I have is that the first request a user makes, the id might not be populated yet. The sessions table has the correct number of entries, but my tracking table does not.
Example Code
class CaptionController < ApplicationController
def index
@image = Image.order("RANDOM()").first
Tracking.log(session.id, Tracking::VIEW_CAPTION_ON_IMAGE, @image.id)
end
The code above results in 50% of the time, the session being nil in the table it logs to.
I found the answer, it looks like Rails is trying to be efficient by only creating a session if there is something to store. So accessing the session.id without storing something doesn't return consistent results.
You need to force the session to be created by storing something in it.
TLDR: Add this somewhere before you access the session ID.
session[:foo] = "bar"
Source: http://www.gani.com.au/2013/08/force-session-creation-in-rails/
这篇关于Rails 4 session.id偶尔无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!