How force that session is loaded?

后端 未结 4 838
南旧
南旧 2020-12-03 10:47

I\'m working on an application that needs to use session id information. My session is stored in cookies. The problem I have is that my session is not immediately available

相关标签:
4条回答
  • 2020-12-03 11:14

    I found a way to force initialization of the session. Accessing the session apparently does not force initialization but writing into the session does. What I do in my controller is this now:

    class MyController < ApplicationController
      protect_from_forgery
      def index
        session["init"] = true
        do_stuff
      end
    end
    

    Still I'm not sure if this should be considered normal behavior in Rails. It doesn't look right to me having to write into the session to force initialization. Reading should be enough.

    0 讨论(0)
  • 2020-12-03 11:14

    I agree with @joscas answer but instead of writing a value, I'd delete it as to not have redundant data.

    class MyController < ApplicationController
      protect_from_forgery
      def index
        session.delete 'init'
        do_stuff
      end
    end
    

    The session is loaded this way too.

    Note: Make sure you don't use the key to be deleted in your application.

    0 讨论(0)
  • 2020-12-03 11:17

    Here's some relevant code from ActionDispatch::Session:

     def [](key)
        load_for_read!
        @delegate[key.to_s]
      end
    
      private
    
      def load_for_read!
        load! if !loaded? && exists?
      end
    

    Which implies that the session object will be loaded as soon as you access any value by its key via [].

    0 讨论(0)
  • 2020-12-03 11:29

    I don't really understand your question. If you require a user to register or sign in before being able to access the site there should be no problem. When creating a user his information is immediately stored in a cookie. For example:

    User controller: (registering is done through users#new)

    def create
       @user = User.new(params[:user])
       if @user.save
         cookies.permanent[:remember_token] = user.remember_token
         redirect_to root_path, notice: "Thank you for registering!"
       else
         render :new
       end
     end
    

    Sessions controller: (signing in is done through sessions#new)

     def create
      user = User.find_by_email(params[:session][:email].downcase)
    
      if user && user.authenticate(params[:session][:password])
        cookies.permanent[:remember_token] = user.remember_token
        redirect_to root_path, notice: "Logged in."
      else
        flash.now.alert = "Email or password is incorrect."
        render :new
     end
    end
    
    0 讨论(0)
提交回复
热议问题