# Sessions

  • Configurations

    If you need a different session storage mechanism, you can change it in an initializer:

    # Use the database for sessions instead of the cookie-based default,
    # which shouldn't be used to store highly confidential information
    # (create the session table with "rails g active_record:session_migration")
    # Rails.application.config.session_store :active_record_store
    
    1
    2
    3
    4

    Rails sets up a session key (the name of the cookie) when signing the session data. These can also be changed in an initializer:

    # Be sure to restart your server when you modify this file.
    Rails.application.config.session_store :cookie_store, key: '_your_app_session'
    
    1
    2

    You can also pass a :domain key and specify the domain name for the cookie:

    # Be sure to restart your server when you modify this file.
    Rails.application.config.session_store :cookie_store, key: '_your_app_session', domain: ".example.com"
    
    1
    2

    Rails sets up (for the CookieStore) a secret key used for signing the session data in config/credentials.yml.enc. This can be changed with bin/rails credentials:edit.

    # aws:
    #   access_key_id: 123
    #   secret_access_key: 345
    
    # Used as the base secret for all MessageVerifiers in Rails, including the one protecting cookies.
    secret_key_base: 492f...
    
    1
    2
    3
    4
    5
    6
  • Accessing Sessions

    In your controller, you can access the session through the session instance method.

    Session values are stored using key/value pairs like a hash:

    class ApplicationController < ActionController::Base
    
      private
    
      # Finds the User with the ID stored in the session with the key
      # :current_user_id This is a common way to handle user login in
      # a Rails application; logging in sets the session value and
      # logging out removes it.
      def current_user
        @_current_user ||= session[:current_user_id] &&
          User.find_by(id: session[:current_user_id])
      end
    end
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
  • Storing Sessions

    To store something in the session, just assign it to the key like a hash:

    class LoginsController < ApplicationController
      # "Create" a login, aka "log the user in"
      def create
        if user = User.authenticate(params[:username], params[:password])
          # Save the user ID in the session so it can be used in
          # subsequent requests
          session[:current_user_id] = user.id
          redirect_to root_url
        end
      end
    end
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
  • Removing Sessions

    To remove something from the session, delete the key/value pair:

    class LoginsController < ApplicationController
      # "Delete" a login, aka "log the user out"
      def destroy
        # Remove the user id from the session
        session.delete(:current_user_id)
        # Clear the memoized current user
        @_current_user = nil
        redirect_to root_url
      end
    end
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

    To reset the entire session, use reset_session.

  • Flash data

    Sometimes you may wish to store items in the session for the next request. You may do so using the flash

    Let's use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:

    class LoginsController < ApplicationController
      def destroy
        session.delete(:current_user_id)
        flash[:notice] = "You have successfully logged out."
        redirect_to root_url
      end
    end
    
    1
    2
    3
    4
    5
    6
    7

    Note that it is also possible to assign a flash message as part of the redirection. You can assign :notice:alertor the general-purpose :flash:

    redirect_to root_url, notice: "You have successfully logged out."
    redirect_to root_url, alert: "You're stuck here!"
    redirect_to root_url, flash: { referral_code: 1234 }
    
    1
    2
    3
    <html>
      <!-- <head/> -->
      <body>
        <% flash.each do |name, msg| -%>
          <%= content_tag :div, msg, class: name %>
        <% end -%>
    
        <!-- more content -->
      </body>
    </html>
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

    You can pass anything that the session can store; you're not limited to notices and alerts:

    <% if flash[:just_signed_up] %>
      <p class="welcome">Welcome to our site!</p>
    <% end %>
    
    1
    2
    3

    # flash.now

    By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the create action fails to save a resource, and you render the new template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use flash.now in the same way you use the normal flash:

    class ClientsController < ApplicationController
      def create
        @client = Client.new(client_params)
        if @client.save
          # ...
        else
          flash.now[:error] = "Could not save client"
          render action: "new"
        end
      end
    end
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
  • Cookies

    Following is the syntax for setting cookies −

    # Set a simple session cookie
    cookies[:user_name] = "david" 
    
    # Set a cookie that expires in 1 hour
    cookies[:login] = { :value => "XJ12", :expires => Time.now + 3600}
    
    1
    2
    3
    4
    5

    Following is the syntax for reading cookies −

    cookies[:user_name]  # => "david"
    cookies.size         # => 2
    
    1
    2

    Following is the syntax for deleting cookies −

    cookies.delete :user_name
    
    1

    All the option symbols for setting cookies are −

    • value − The cookie.s value or list of values (as an array).
    • path − The path for which this cookie applies. Defaults to the root of the application.
    • domain − The domain for which this cookie applies.
    • expires − The time at which this cookie expires, as a +Time+ object.
    • secure − Whether this cookie is a secure cookie or not (default to false). Secure cookies are only transmitted to HTTPS servers.