How to Set Cookie in Ruby on Rails?
Last Updated :
02 Apr, 2024
Cookies are small pieces of data that are sent from a website and stored on the user's computer by the user's web browser. They are commonly used for session management, user authentication, personalization, and tracking.
In Ruby on Rails, you can use the 'cookies' object to set, read, and delete cookies within your Rails application. It is commonly used in controllers to create the server-side logic, but you can use it in views too.
Steps to Set Cookies in Ruby on Rails
Step 1: Create a demo project using the command below. It will create a project named 'myapp' in the current directory. Then use the second command to get into your project directory.
rails new myapp
cd myapp
create a demo projectStep 2: Next, generate a controller and a view(web page) using the command below. It will create a controller file 'home_controller.rb' in ‘app/controllers’ and corresponding view file 'index.html.erb' which is our webpage in ‘app/views/home’. It will also create a route in ‘app/config/routes.rb’.
rails generate controller home index
generate controller and viewStep 3: Now, configure the root to access the index page every time you run the server. Open 'config/routes.rb' and add the following line.
root 'home#index'
Configure routesStep 4: Now, open 'app/controllers/home_controller.rb' and add the following code to set a cookie in the 'index' action.
The cookie will be set when the corresponding action in your controller is executed. In our case, the cookie will be set when the 'index' action of the 'HomeController' is invoked. In simple words, when someone accesses the home page of our application, the code will set the cookie.
Ruby
class HomeController < ApplicationController
def index
cookies[:name] = {
value: "GeeksforGeeks",
expires: 1.week.from_now
}
end
end
This code sets a cookie named 'user_id' with the value "123", and it will expire in 1 week. You can specify other parameters also such as ':domain' , ':path' , ':secure' , ':httponly' and 'tld_length'.
- ':domain': The ':domain' option allows you to specify the domain for which the cookie is valid. For example, setting 'domain : .geeksforgeeks.org' would make the cookie accessible to all subdomains of geeksforgeeks.org.
- ':path': The path for which this cookie applies. The default is the root of the application('/').
- ':secure': When you set the ':secure' option to true, the cookie will only be sent by the browser over HTTPS connections. The default value is false.
- ':httponly': When you set the ':httponly' option to true prevents the cookie from being accessed via JavaScript. Then it can be accessed using HTTP only. The default value is false.
- ':tld_length': Top level domains consist of multiple parts (eg. .co.in, .com.us). ':tld_length' is used with ':domain' to determine how many parts of the domain name should be considered as the TLD. The default value is 1.
Step 5: Now, Write a message in 'app/views/home/index.html.erb' which will be displayed you access the home page.
HTML
<!DOCTYPE html>
<html>
<head>
<title>GeeksforGeeks</title>
</head>
<body>
<h1>Cookie Set Successfully</h1>
</body>
</html>
Step 6: Finally, start the Rails server to see the output. After executing the command, open 'http://localhost:3000' in your browser.
rails server
Output:
OutputNow, to check if the cookie is set or not you can go to 'http://localhost:3000', right-click and select 'inspect'. Navigate to 'Application' tab, expand the 'Cookies' section in 'Storage' and you can see your cookies.
View cookiesHere you can see the value of cookie which is 'GeeksforGeeks' and it will expire in 1 week.
Similar Reads
How to create table in Ruby on Rails?
In Ruby on Rails, creating tables involves using migrations, which are a powerful mechanism for managing database schema changes. Here's a detailed breakdown of the process: 1. Database Setup (Optional): While APIs can function without databases, many Rails applications use them for data persistence
3 min read
How to Upload Files in Ruby on Rails?
Uploading files in a web application is a common requirement, whether it's for user profile pictures, documents, or any other files. Ruby on Rails makes this task straightforward with its built-in tools. In this article, we'll walk through the steps to set up file uploads in a Rails app, from creati
6 min read
How to Add CSS in Ruby on Rails?
This article focuses on discussing how to add Cascading Style Sheets (CSS) in Ruby on Rails. Table of Content Using SCSSUsing Plain CSSUsing Inline StylesUsing External CSS FrameworksComparison of Different ApproachesAdditional ConsiderationsConclusionUsing SCSSSCSS (Sass) is a preprocessor that ext
4 min read
How to create API in Ruby on Rails?
Building APIs with Ruby on Rails: A Step-by-Step GuideRuby on Rails (Rails) is a popular framework for web development, known for its convention over configuration approach. It also excels in creating robust and maintainable APIs (Application Programming Interfaces). APIs act as intermediaries, allo
3 min read
Ruby on Rails - How to Send Emails?
Email communication is a must-have function for those who want their web application to keep up with the current trend. The Action Mailer Framework of Ruby on Rails helps to make the tasks of sending emails easier. This article focuses on discussing sending emails using Ruby on Rails.Table of Conten
11 min read
How to create model in Ruby on Rails?
In Ruby on Rails, models are like the organizers of your data. They handle interactions with your database. Think of them as the brains of your application, responsible for managing and manipulating data. They represent the structure and behavior of the information your app works with. So, whenever
4 min read
How to Set File Path in Ruby?
In Ruby, setting and working with file paths is a common task, whether you're reading from or writing to files. Ruby provides several ways to work with file paths, offering both simplicity and flexibility. This guide will explain how to set a file path in Ruby, covering basic usage and best practice
4 min read
How to Create Button in Ruby on Rails?
Ruby on Rails, commonly known as Rails, is a popular web application framework written in the Ruby programming language. It follows the Model-View-Controller (MVC) architectural pattern, which separates the application's data, logic, and user interface components. Rails emphasizes convention over co
7 min read
How to Add Image in Ruby on Rails?
In Ruby on Rails, there are several ways to add images to your application. In this article, we will see one of the common methods which is using an assets pipeline.Steps on How to Create a ProjectStep 1: Create a demo project using the command below. It will create a project named 'myapp' in the cu
2 min read
How to Convert Hash to JSON in Ruby?
Ruby Hash is an unordered set of data in key-value pairs. These are mutable and can store multiple data types. JSON stands for Javascript Object Notation and is a human-readable file format that is commonly used in web services and API calls. In this article, we will discuss how to convert a hash to
2 min read