Zack
Zack

Reputation: 671

Where does 'session' come from?

I'm building a sessions controller in my rails app, and I'm just not sure why something is working here. In the create and destroy actions, session[index] is assigned to either nil or a user id. But this sessions hash isn't defined anywhere (as far as I can see). Why is this working? Can anyone clarify this for me?

(for the sake of clarity, there is no sessions model)

  class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.find_by_email(params[:email])
    if user && user.authenticate(params[:password])
        session[:user_id] = user.id
        redirect_to products_url, :note => "Logged in!"
    else
        render "new"
  end

  def destroy
    session[:user_id] = nil
    redirect_to products_url, :notice => "Logged out!"
  end
end

Upvotes: 2

Views: 231

Answers (2)

richsinn
richsinn

Reputation: 1331

By default sessions are stored in a cookie in the client-side (i.e. the user's browser's cookie). It is not stored on the server-side (i.e. where the Rails app is actually running.)

When you use the session hash, Rails is smart enough to look/ask for the session information accordingly. In the default case, Rails knows to set the session information in the browser's cookie, or retrieve the information from the browser's cookie.

You can also pick where to put your session store by setting the config.session_store configuration variable.

See the Rails guide for more info.

Upvotes: 1

Daniel Kehoe
Daniel Kehoe

Reputation: 10952

The session instance method functions like a Hash and is part of the Rails API.

Rails does all the work of setting up an encrypted, tamperproof session datastore. By default, session data is saved as a cookie in the browser. You can specify other storage mechanisms but CookieStore is the default and the most convenient.

The CookieStore default is set in the config/initializers/session_store.rb file:

Rails.application.config.session_store :cookie_store, key: '_learn-rails_session'

You can learn more about sessions in Rails:

For more information, I've written a Rails Devise Tutorial that shows how sessions are managed with the Devise authentication gem.

Upvotes: 3

Related Questions