Rails 4 session.id is sometimes zero

I am running a simple site on Heroku and I notice something strange when I start the application. It looks like roughly 50-60% of my users report nil session_id when it logs into my database.

I am using active_record_store for my session handler and Postgres as my db server. I got similar results using cookie_store, so I'm not sure what I am doing wrong. The only thing I have is that the first user request is making, the id is not yet populated. The sessions table has the correct number of records, but my tracking table does not.

Sample code

class CaptionController < ApplicationController

  def index

    @image = Image.order("RANDOM()").first
    Tracking.log(session.id, Tracking::VIEW_CAPTION_ON_IMAGE, @image.id)

  end

      

The above code gives the result 50% of the time, and the session is zero on the table it belongs to.

+3


source to share


1 answer


I found the answer, it looks like Rails is trying to be efficient by only creating a session if there is something to store. Therefore, accessing session.id without saving anything does not lead to consistent results.

You need to force the session to create by storing something in it.

TL; DR: 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/

+5


source







All Articles