Sessions in Ruby on Rails provide a way to store data between multiple requests from the same user. This is essential for maintaining user state, such as keeping users logged in as they navigate through different pages.
Rails supports multiple ways to store session data. The most common storage mechanisms are:
Configure session storage in config/application.rb or environment-specific files: # config/application.rb module YourApp class Application < Rails::Application config.session_store :cookie_store, key: '_your_app_session' # Other options: # config.session_store :active_record_store, key: '_your_app_session' # config.session_store :cache_store, key: '_your_app_session' # config.session_store :redis_store, servers: "redis://localhost:6379/0/session" end end
Interact with session data using the session hash: class SessionsController < ApplicationController def create user = User.find_by(email: params[:email]) if user && user.authenticate(params[:password]) session[:user_id] = user.id redirect_to root_path, notice: "Logged in!" else flash.now[:alert] = "Invalid email or password" render :new end end end