简体   繁体   English

如何在cookie导轨4上存储数组?

[英]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. 我使用cookies[:test] = Array.new ,当我尝试解码@test = ActiveSupport :: JSON.decode(cookies [:test])时,出现错误。 Whats the proper way to achieve what I am trying to ? 什么是实现我正在尝试的正确方法?

When writing to the cookie I usually convert the array to a string. 当写入cookie时,我通常将数组转换为字符串。

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

Then I convert back into an array when reading the cookie. 然后我在读取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. 我不确定这是否是“正确的方法”,但对我来说效果很好。

The "Rails way" is to use JSON.generate(array) , since it's what is used in the second example in the Cookies docs: “ Rails方式”是使用JSON.generate(array) ,因为它是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 来源: 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. 当您想读回它时,只需使用JSON.parse cookies[:lat_lon]例如,它将为您提供一个数组。

Use session , not cookies . 使用session ,而不是cookies You don't have to decode it, rails handles that for you. 您不必解码它,Rails会为您处理。 Create the session the same way you already are: 以与现有相同的方式创建会话:

session[:test] = Array.new

and when you need it, access it like normal 并在需要时像平常一样访问它

session[:test]
# => []

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM