Eric Luo Eric Luo - 6 months ago 62
Ruby Question

Array become string when passing in session in Rails 4

I have an array as key in a hash stored in session in Rails.
The code looks like:

array = ["a", "b"]
session[:likes] ||= {}
session[:likes][array] ||= []
session[:likes][array] = ["c", "d"]


However, the output looks like:

> session[:likes]
> {"[\"a\", \"b\"]"=>["c", "d"]}


Why would my array become a string?
Is there any way to prevent my array becoming string?

Update and Alternative:

I end up using
join(",")
to convert the array to a string
"a,b"
before saving into session. Then use 'split(",")' to convert the string to array
[a,b]

Answer

Why would my array become a string?

The Rails session store use a json serialization. json can't have an array as key:

=> a
=> {:likes=>{["a"]=>["b", "b"]}}
=> a.to_json
=> "{\"likes\":{\"[\\\"a\\\"]\":[\"b\",\"b\"]}}"
=> JSON.parse a.to_json
=> {"likes"=>{"[\"a\"]"=>["b", "b"]}}

That's why your array become a string.

Is there any way to prevent my array becoming string?

While you use the json serialization, no way.