AdamNYC
AdamNYC

Reputation: 20415

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 situation: I have an input field (say, address) that user needs to fill out when s/he first comes to my site. The user then logs in using Omniauth. I would like to persist address until after he logs in.

Update: I was able to add to document.cookies on client. However, cookies["something"] returns nil from Rails end. Below is the cookie hash:

#<ActionDispatch::Cookies::CookieJar:0x007 @secret="f4d518c0b2", @set_cookies={}, @delete_cookies={}, @host="localhost", @secure=false, @closed=false, @cookies={"_myapp_session"=>"BAh7Ck==--776b2fcfcd63d3c84d2b1de5327e277499add6d4", "fbsr_1505068851081"=>"mqZeyvoRC"}, @signed=#<ActionDispatch::Cookies::SignedCookieJar:0x007 @parent_jar=#<ActionDispatch::Cookies::CookieJar:0x007fdf...>, @verifier=#<ActiveSupport::MessageVerifier:0x007fdfa34548d8 @secret="f4d518c0b2e9d8", @digest="SHA1", @serializer=Marshal>>>

Upvotes: 3

Views: 7971

Answers (3)

rebagliatte
rebagliatte

Reputation: 2146

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.

Upvotes: 2

Jugulum
Jugulum

Reputation: 21

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

Upvotes: 0

Kaeros
Kaeros

Reputation: 1138

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.

Upvotes: 12

Related Questions