使用的ActiveRecord在数据库中存储阵列阵列、数据库中、ActiveRecord

2023-09-09 21:59:39 作者:帅的很低调

我在轨2.3.8和放大器;我使用MySQL作为数据库适配器。 我想存储阵列在我的数据库。搜索后,我可以用这个非常有用的article.

I am on rails 2.3.8 & I am using mysql as db adapter. I want to store arrays in my database. After searching I could come up with this very useful article.

现在我需要使用图形用户界面的输入和放大器;不仅服务器控制台。所以说,我有一个逻辑上应该有int数组的文本字段名为NUMS。应该是什么NUMS的,以便可以容易检索和安培的格式;数组存储了该字符串的?

Now I need to use GUI for input & not only server console. So say I have a text field called nums which logically should have int array. What should be the format of nums so that it becomes easy to retrieve & store the array out of that string ?

推荐答案

如果您使用连载那么你不应该担心如何将数据存储在该文本字段,但它实际上是YAML。

If you use serialize then you shouldn't have to worry about how the data is stored within the text field, although it's actually YAML.

连载被记录在滑轨/ ActiveRecord的API (向下滚动到标题为保存数组,哈希,以及其他非可映射在文本列对象一节)

serialize is documented in the Rails/ActiveRecord API (scroll down to the section headed "Saving arrays, hashes, and other non-mappable objects in text columns")

有关显示,你需要的格式,是可以理解的用户,并可以很容易地转换回在code数组。逗号或空格分隔?

For display, you need a format that is understandable to users and that can be easily converted back into an array in your code. Comma- or space-delimited?

格式输出:

delim = ',' # or ' ' for spaces, or whatever you choose
array.join(delim)

转换回一个数组可能的工作方式如下:

Converting back into an array might work as follows:

num_array = nums.split(delim).map(&:to_i) # or to_f if not integers

或者使用字符串#扫描?

or perhaps using String#scan?

num_array = nums.scan(/\d+/).map(&:to_i) # for positive integers