![]() |
VOOZH | about |
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.
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
Step 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
Step 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'
Step 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.
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'.
Step 5: Now, Write a message in 'app/views/home/index.html.erb' which will be displayed you access the home page.
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:
Now, 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.
Here you can see the value of cookie which is 'GeeksforGeeks' and it will expire in 1 week.