Luis Ortega Araneda
Luis Ortega Araneda

Reputation: 875

How to store multiple values inside one cookie in Ruby on Rails?

I'm learning how to work with cookies in Ruby on Rails. All I know is how to set the name and the value of a cookie, but I want to store up to three more fields. So any hints or good tutorials would be appreciated!

Thanks for any help.

Upvotes: 3

Views: 3264

Answers (3)

LightBox
LightBox

Reputation: 3425

You can assign an array to a cookie in rails with

cookies[:my_array] = [12, 1234]

and read the array

cookies[:my_array]   # => [12, 1234]

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

Upvotes: 1

ALoR
ALoR

Reputation: 4914

The best option in this case it to use the server-side session to store the three values and let the cookie be just the reference to that session. On the client side you will have just one value (the session identified by some sort of UUID) and on the server you can have as many value as you want in memory.

Upvotes: 1

FilipK
FilipK

Reputation: 626

Cookies by definition consist of a single name / value pair, where both fields are text. You should really be using three separate cookies to store separate values.

cookies["value_1"] = "one"
cookies["value_2"] = "two"
cookies["value_3"] = "three"

If for some reason you can't or don't want to have more than one cookie, you can put different values joined with a separator (an arbitrary text like ~~ in the following example):

value_1 = "one"
value_2 = "two"
value_3 = "three"
cookies["multiple_values"] = "#{value_1}~~#{value_2}~~#{value_3}"

But that way, you'll have to parse the cookie back, retrieving values by splitting the cookie value using your separator text. There's danger however that one day a proper value will contain your separator and ruin the parsing process.

Upvotes: 5

Related Questions