Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 session.id occasionally nil

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.

like image 382
Gabe Brown Avatar asked Feb 09 '23 21:02

Gabe Brown


1 Answers

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/

like image 142
Gabe Brown Avatar answered Feb 12 '23 10:02

Gabe Brown