How to Use Session in Rails: Simple Guide with Examples
In Rails, you use the
session hash to store data between requests for a user. You can set values like session[:user_id] = 1 and read them back with session[:user_id]. This lets you keep track of user state, such as login status, across pages.Syntax
The session in Rails is a hash-like object available in controllers and views. You can store data by assigning a value to a key, and retrieve it by accessing that key.
session[:key] = value— storesvalueunder:key.session[:key]— retrieves the stored value.session.delete(:key)— removes the key and its value from the session.
ruby
class ApplicationController < ActionController::Base def set_session session[:user_name] = "Alice" end def get_session @user_name = session[:user_name] end def clear_session session.delete(:user_name) end end
Example
This example shows a simple login simulation where the user's name is stored in the session when they 'log in', and displayed on another page.
ruby
class SessionsController < ApplicationController def create # Simulate login by storing user name in session session[:user_name] = params[:user_name] redirect_to welcome_path end def welcome @user_name = session[:user_name] end def logout session.delete(:user_name) redirect_to login_path end end # routes.rb Rails.application.routes.draw do get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' get '/welcome', to: 'sessions#welcome' delete '/logout', to: 'sessions#logout' end # sessions/new.html.erb <%= form_with url: '/login', method: :post do %> <label for="user_name">Name:</label> <input type="text" name="user_name" id="user_name" /> <button type="submit">Log In</button> <% end %> # sessions/welcome.html.erb <% if @user_name %> <p>Welcome, <strong><%= @user_name %></strong>!</p> <%= button_to 'Log Out', '/logout', method: :delete %> <% else %> <p>Please log in first.</p> <% end %>
Output
When you submit the login form with a name, the page at /welcome shows: "Welcome, Alice!" and a Log Out button. After logout, it redirects to login page.
Common Pitfalls
Common mistakes when using sessions in Rails include:
- Trying to store large objects or complex data structures in the session, which can cause performance issues.
- Not clearing session data on logout, which can lead to security risks.
- Assuming session data is permanent; sessions expire or can be cleared by the user.
- Using string keys instead of symbols, which is allowed but less common and can cause confusion.
ruby
class SessionsController < ApplicationController
def logout_wrong
# Wrong: forgetting to clear session
redirect_to login_path
end
def logout_right
# Right: clear session data
session.delete(:user_name)
redirect_to login_path
end
endQuick Reference
Remember these key points when using sessions in Rails:
- Use
session[:key] = valueto store data. - Access data with
session[:key]. - Remove data with
session.delete(:key). - Keep session data small and simple.
- Clear session on logout to protect user data.
Key Takeaways
Use the session hash to store and retrieve user data between requests in Rails.
Always clear sensitive session data on logout to maintain security.
Keep session data small to avoid performance issues.
Access session data with symbol keys like session[:user_id].
Sessions are temporary and can expire or be cleared by the user.