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 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 Remove a Cookie in PHP? Cookies are small text files stored in a user's browser. It contain data such as user preferences, session information, and other relevant details. PHP cookies are used to store information that can persist across different web pages or sessions. At times, you may need to delete or remove a cookie,
4 min read
Ruby On Rails Session 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 developmen
5 min read
How to create, handle and validate forms in Ruby on Rails? Forms are one of the basic elements of any web application because they allow for information submission, such as name, email address, phone number, and other required information whether one is signing up for a new account, sending a contact form, or posting news updates. These factors make Ruby on
7 min read