How to Use Cookies in Ruby on Rails

09/20/2021

Contents

In this article, you will learn how to use cookies in Ruby on Rails.

Using cookies

Cookies are a useful way to store data on a user’s browser for future use. In Ruby on Rails, you can use the cookies object to set, get, and delete cookies.

Here are the basic steps to use cookies in Ruby on Rails:

Set a cookie

To set a cookie, use the cookies object and call the []=() method, passing in the cookie name and value as arguments. For example:

cookies[:user_id] = 123

This will set a cookie named “user_id” with a value of 123.

Get a cookie

To retrieve a cookie value, use the cookies object and call the []() method, passing in the cookie name as an argument. For example:

user_id = cookies[:user_id]

This will retrieve the value of the “user_id” cookie and store it in the user_id variable.

Delete a cookie

To delete a cookie, use the cookies object and call the delete() method, passing in the cookie name as an argument. For example:

cookies.delete(:user_id)

This will delete the “user_id” cookie.

Note that when setting a cookie, you can also specify additional options such as the cookie expiration time, the domain or path to which the cookie applies, and whether the cookie should be secure or not. For example:

cookies[:user_id] = {
  value: 123,
  expires: 1.hour.from_now,
  domain: "example.com",
  path: "/",
  secure: true
}

This will set a cookie with a value of 123 that expires in 1 hour, applies to the “example.com” domain and the root path, and is marked as secure.