Reputation: 20415
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
Reputation: 2146
Short Answer
Install the MDN JavaScript Cookie Framework
On your js file:
docCookies.setItem('my_cookie', 'my_cookie_value', '', '/');
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
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
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