Skip to content Skip to sidebar Skip to footer

Set A Cookie From View, Then Read It From Controller In Rails

I would like to set cookie value from within Rails view using Javascript, then use Controller to read this cookie. Is this possible with Rails, and how should I go about it? My sit

Solution 1:

To set a cookie in javascript you can do:

document.cookie="something= test";

So you can add an event (click, submit, ..) to get the value from the input and create a cookie the way i mentioned above.

In rails you can read the value like this:

cookies["something"]

You can also specify when the cookie will expire in javascript if you need to.

Solution 2:

Short Answer

  1. Install the MDN JavaScript Cookie Framework

  2. On your js file:

    docCookies.setItem('my_cookie', 'my_cookie_value', '', '/');
    
  3. On your rails controller:

    cookies[:my_cookie]

Not so short answer

Rails ActionDispatch::Cookies defaults the cookie path to the root of the application, while plain JavaScript defaults it to the current path.

This means that if you don't declare the path, you'll end up with two different cookies bearing the same name and a headache.

In order to troubleshoot this you can use the 'Application/Cookies' on the Chrome DevTools window so you can see all the details for each cookie and reload their values as you modify them via the 'Console' panel.

Solution 3:

This may explain your problem. Apparently you need to make sure the cookie's path lines up.

How can i read cookies in rails that have been set by jquery

Post a Comment for "Set A Cookie From View, Then Read It From Controller In Rails"