如何使用rails存储cookie中的值数组?

时间:2021-12-15 15:41:47

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.

我想在cookie中保存一组值。我有一个名为add_names的方法。每当调用此方法时,我都需要在cookie中保存名称。我试过下面的代码。但它不起作用,它只保留最后一个值。

def add_names(name)
  cookies[:user_names] = name
end

Please suggest me a idea to do this. Thanks in advance.

请建议我这样做的想法。提前致谢。

2 个解决方案

#1


2  

Cookies store strings in it. Still if you need to store list of user names you can append names

Cookies存储字符串。如果您需要存储用户名列表,还可以附加名称

cookies[:user_names] = '' if cookies[:user_names].nil?
cookies[:user_names] = cookies[:user_names] + "#{value} ,"

#2


1  

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.

问题是在每个循环中,您将:user_names cookie的值重新定义为单个用户。

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

#1


2  

Cookies store strings in it. Still if you need to store list of user names you can append names

Cookies存储字符串。如果您需要存储用户名列表,还可以附加名称

cookies[:user_names] = '' if cookies[:user_names].nil?
cookies[:user_names] = cookies[:user_names] + "#{value} ,"

#2


1  

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.

问题是在每个循环中,您将:user_names cookie的值重新定义为单个用户。

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