Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set cookie value in JavaScript and get it in Rails controller

Using Ruby on Rails 5.0.3 .

I want to set some value in cookie using JavaScript (when button clicked), and get it in Rails.

I know how to access session in Rails, which is session[:some_key] or cookies.

But I don't know how to do in JavaScript. (it must be able to accessed from Rails session or cookies.)

How can I do it in JS?

Or any other ways to save some value in JS, and get it later in Rails ?

like image 612
Taichi Avatar asked Sep 19 '25 05:09

Taichi


2 Answers

Unfortunately, you can't modify Rails session from the client side, even if it stored in cookies. Because the rails session is encrypted. As a solution, you can use regular cookies, not the Rails session.

Check http://api.rubyonrails.org/v5.1/classes/ActionDispatch/Cookies.html https://www.w3schools.com/js/js_cookies.asp for more information.

like image 165
Alex Tatarnikov Avatar answered Sep 21 '25 18:09

Alex Tatarnikov


The cookie for the rails app is just some hashed string to ID the server cookie, which has the data.

What they said, use Ajax to some controller method you write to update your necessary info into the rails cookie.

like image 24
Sam Sabey Avatar answered Sep 21 '25 19:09

Sam Sabey