Ruby on Rails is a powerful web application framework written in the Ruby programming language. It follows the convention over configuration principle, enabling developers to build applications quickly and efficiently.
Rails emphasizes the use of RESTful design patterns and encourages the development of clean, maintainable code. With its rich set of tools and libraries, Ruby on Rails simplifies the process of web development, making it accessible for beginners and robust for developers.
Table of Content
Ruby on Rails Session
A session within Ruby on Rails is used for the temporary storage of information while the user is interacting with your application. It is available for the user as they navigate to various different pages. For example, once a user logs into an application, their details can be kept in session so they will not have to log into your application on each page.
By default, Rails stores session data in cookies (small pieces of data) stored in your browser. In addition to this, you can also store session data in a database or elsewhere, if you so desire.
Key Features of Sessions
- Persistence: Session data is persisted during the entire visit of the user to the application.
- Security: Rails sessions are signed and encrypted, meaning sensitive information cannot be tampered with, neither can unauthorized access to the info occur.
- Flexibility: You can store many types of data in a session, like strings, numbers, arrays, or even objects.
Accessing the Session
It is pretty easy to use sessions in Rails. You can access the session object from any controller. It's essentially a hash (a collection of key-value pairs).
Basic Operations
Reading from the Session:
user_id = session[:user_id]
This code reads the user_id value stored in the session.
Writing to the Session:
session[:user_id] = @user.id
This code saves the userâs ID to the session.
Deleting a Session Key:
session.delete(:user_id)
This code removes the user_id from the session.
Example of Session in a Simple Rails App
Let's create a simple Rails application that shows user login functionality using sessions. This example will make sure it can store user information in the session after login and how to access in subsequent requests.
Step 1: Create a New Rails Application
Create a new Rails app by running these commands in your terminal:
rails new session_example
cd session_example // Command to change the directory
Step 2: Create a Users Controller
Generate a controller for handling user sessions
rails generate controller Users new create destroy
Step 3: Set Up Routes
In the config/routes.rb file, add the necessary routes for login, logout, and the homepage:
Rails.application.routes.draw do
root 'users#new' # The root path shows the login form for this example
get 'login', to: 'users#new' # Route for displaying the login form
post 'login', to: 'users#create' # Route for processing the login form
delete 'logout', to: 'users#destroy' # Route for logging out the user
end
Step 4: Create a Login Form
In app/views/users/new.html.erb, create a basic login form that will allow users to log in by entering a username:
<h1>Login</h1>
<%= form_with url: login_path, method: :post do %>
<div>
<%= label_tag :username %>
<%= text_field_tag :username %>
</div>
<div>
<%= submit_tag "Login" %>
</div>
<% end %>
Step 5: Implementing the UsersController
Now, we add both create and destroy actions by implementing the following code in app/controllers/users_controller.rb. This is the login action that captures a user's ID in the session, and a destroy action that clears the session.
class UsersController < ApplicationController
def new
end
def create
# Fake user authentication for this example
if params[:username] == "admin"
session[:user_id] = 1
flash[:notice] = "Successfully logged in!"
redirect_to root_path
else
flash[:alert] = "Invalid username"
render :new
end
end
def destroy
session[:user_id] = nil
flash[:notice] = "Logged out successfully!"
redirect_to login_path
end
end
Step 6: Display the Logged-in User
Add following lines in the homepage view at app/views/welcome/index.html.erb showing logged-in user's data: Indicate whether there is some user_id stored in the session so that he can figure out whether the user is logged-in or not:
<h1>Welcome to the Session Example</h1>
<% if session[:user_id] %>
<p>Logged in as: Admin</p>
<%= link_to 'Logout', logout_path, method: :delete %>
<% else %>
<p>You are not logged in.</p>
<%= link_to 'Login', login_path %>
<% end %>
Step 7: Update Application.html.erb file
<!DOCTYPE html>
<html>
<head>
<title><%= content_for(:title) || "Session Example" %></title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= yield :head %>
<link rel="manifest" href="/manifest.json">
<link rel="icon" href="/icon.png" type="image/png">
<link rel="icon" href="/icon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="/icon.png">
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
<%= javascript_importmap_tags %>
</head>
<body>
<header>
<% if session[:user_id] %>
<p>Logged in as: Admin</p>
<%= form_with url: logout_path, method: :delete do %>
<%= submit_tag 'Logout' %>
<% end %>
<% else %>
<%= link_to 'Login', register_path %>
<% end %>
</header>
<% if notice %>
<p><%= notice %></p>
<% end %>
<%= yield %>
</body>
</html>
Step 8: Run the Application
Start the Rails server and test whether the session app is working or not.
rails server
visiting http://localhost:3000 for output.
Output
Conclusion
Sessions in Ruby on Rails enables you to track user data as you navigate through your web application with ease. We have seen how to access sessions, store and retrieve data from them, and we even created a basic login system using sessions.
Now that we've covered how to understand how to work with sessions, this topic will surely bring you up the ante to develop better, more dynamic Rails applications that remember user activity across multiple pages.