How to store array on a cookie rails 4?

前端 未结 3 1043
再見小時候
再見小時候 2021-01-20 01:03

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 = ActiveSupp

3条回答
  •  梦毁少年i
    2021-01-20 02:03

    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.

提交回复
热议问题