How to store an array on cookie rails 4?

I am trying to save an array on rails, getting an error while decoding. I use cookies[:test] = Array.new And when I try to decode @test = ActiveSupport :: JSON.decode (cookie files [: test]) I get an error message. What is the right way to achieve what I'm trying to do?

+4
source share
3 answers

Use session , not cookies . You do not need to decrypt it, the rails handle this for you. Create a session just like you:

 session[:test] = Array.new 

and when you need it, refer to it as usual.

 session[:test] # => [] 
-4
source

When writing to a cookie, I usually convert the array to a string.

 def save_options(options) cookies[:options] = (options.class == Array) ? options.join(',') : '' end 

Then I convert back to array when reading the cookie.

 def options_array cookies[:options] ? cookies[:options].split(",") : [] end 

I am not sure if this is the โ€œright wayโ€, but it works well for me.

+5
source

The "Rails way" should use JSON.generate(array) , as it is used in the second example in cookies:

 # Cookie values are String based. Other data types need to be serialized. cookies[:lat_lon] = JSON.generate([47.68, -122.37]) 

Source: http://api.rubyonrails.org/classes/ActionDispatch/Cookies.html

If you want to read it, just use JSON.parse cookies[:lat_lon] , for example, and it will provide you with an array.

+4
source

Source: https://habr.com/ru/post/1502505/


All Articles