Petran
Petran

Reputation: 8087

How to store array on a cookie rails 4?

I am trying to store an array on rails an getting error on the decoding. I use cookies[:test] = Array.new And when I am trying to decode @test = ActiveSupport::JSON.decode(cookies[:test]) I am getting an error. Whats the proper way to achieve what I am trying to ?

Upvotes: 5

Views: 5140

Answers (3)

sandre89
sandre89

Reputation: 5918

The "Rails way" is to use JSON.generate(array), since it's what is used in the second example in the Cookies docs:

# 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

When you want to read it back, just use JSON.parse cookies[:lat_lon] for example, and it'll provide you an array.

Upvotes: 6

Stenerson
Stenerson

Reputation: 1002

When writing to the 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 into an array when reading the cookie.

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

I'm not sure if this is "the right way" but it works well for me.

Upvotes: 5

lightswitch05
lightswitch05

Reputation: 9428

Use session, not cookies. You don't have to decode it, rails handles that for you. Create the session the same way you already are:

session[:test] = Array.new

and when you need it, access it like normal

session[:test]
# => []

Upvotes: -5

Related Questions