使用 ActiveRecord 在数据库中存储数组 [英] Storing arrays in database using ActiveRecord

查看:21
本文介绍了使用 ActiveRecord 在数据库中存储数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Rails 2.3.8 &我使用 mysql 作为数据库适配器.我想在我的数据库中存储数组.搜索后我可以想出这个非常有用的 文章.

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.

现在我需要使用 GUI 进行输入 &不仅是服务器控制台.所以说我有一个名为 nums 的文本字段,它在逻辑上应该有 int 数组.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 ?

推荐答案

如果你使用 serialize 那么你就不必担心文本字段中的数据是如何存储的,尽管它实际上是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.

serialize 记录在 Rails/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")

为了显示,您需要一种用户可以理解的格式,并且可以在您的代码中轻松地将其转换回数组.逗号分隔还是空格分隔?

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

或者也许使用 String#scan?

or perhaps using String#scan?

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

这篇关于使用 ActiveRecord 在数据库中存储数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆