Reputation: 3764
I want to save an array of values in cookie. I have a method called add_names. Whenever this method has been called i need to save the name in the cookie. I have tried the below code. But it's not working, it's keeping only the last value.
def add_names(name)
cookies[:user_names] = name
end
Please suggest me a idea to do this. Thanks in advance.
Upvotes: 0
Views: 1393
Reputation: 654
Cookies store strings in it. Still if you need to store list of user names you can append names
cookies[:user_names] = '' if cookies[:user_names].nil?
cookies[:user_names] = cookies[:user_names] + "#{value} ,"
Upvotes: 2
Reputation: 5378
The easiest way is to do this:
cookies[:user_names] = @users.map { |user| user.name }
The problem is that in your each
loop, you're redefining the value of the :user_names
cookie to be a single user.
If you want to append a value to an existing array, then you can do this:
def add_names name
# Initialize it to an empty array, if not set
cookies[:user_names] ||= []
# Then, append the user name
cookies[:user_names] << name
end
Upvotes: 1