Ruby on rails 使用ActiveRecord在数据库中存储数组

Ruby on rails 使用ActiveRecord在数据库中存储数组,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我在Rails2.3.8上&我使用mysql作为db适配器。 我想在数据库中存储数组。经过搜索,我可以想出这个非常有用的 现在我需要使用GUI进行输入&而不仅仅是服务器控制台。假设我有一个名为nums的文本字段,逻辑上应该有int数组。nums的格式应该是什么,以便从该字符串中检索和存储数组变得容易?如果使用序列化,则不必担心数据如何存储在文本字段中,尽管它实际上是YAML serialize记录在中(向下滚动到标题为“在文本列中保存数组、哈希和其他不可映射的对象”的部分) 对于显示,您需要一种

我在Rails2.3.8上&我使用mysql作为db适配器。 我想在数据库中存储数组。经过搜索,我可以想出这个非常有用的


现在我需要使用GUI进行输入&而不仅仅是服务器控制台。假设我有一个名为nums的文本字段,逻辑上应该有int数组。nums的格式应该是什么,以便从该字符串中检索和存储数组变得容易?

如果使用
序列化
,则不必担心数据如何存储在文本字段中,尽管它实际上是YAML

serialize
记录在中(向下滚动到标题为“在文本列中保存数组、哈希和其他不可映射的对象”的部分)

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

输出格式:

delim = ',' # or ' ' for spaces, or whatever you choose
array.join(delim)
将其转换回数组可能会按如下方式工作:

num_array = nums.split(delim).map(&:to_i) # or to_f if not integers
或者使用字符串扫描


如果您使用的是postgres和rails 4,那么现在您有了更好的本机选项

# db/migrate/20140207133952_create_books.rb
create_table :books do |t|
  t.string 'title'
  t.string 'tags', array: true
  t.integer 'ratings', array: true
end
add_index :books, :tags, using: 'gin'
add_index :books, :ratings, using: 'gin'

# app/models/book.rb
class Book < ActiveRecord::Base
end

# Usage
Book.create title: "Brave New World",
            tags: ["fantasy", "fiction"],
            ratings: [4, 5]

## Books for a single tag
Book.where("'fantasy' = ANY (tags)")

## Books for multiple tags
Book.where("tags @> ARRAY[?]::varchar[]", ["fantasy", "fiction"])

## Books with 3 or more ratings
Book.where("array_length(ratings, 1) >= 3")
#db/migrate/2014020713952_create_books.rb
创建表格:书籍不需要|
t、 字符串“title”
t、 字符串“tags”,数组:true
t、 整数“评级”,数组:真
结束
添加索引:books,:tags,使用'gin'
使用“gin”添加索引:books,:ratings
#app/models/book.rb
类目数组[?]::varchar[],[“幻想”,“小说])
##评级为3级或3级以上的书籍
其中(“数组长度(评级,1)>=3”)

谢谢,迈克。:)我已经弄明白了。一种更简单(尽管容易出错)的方法是直接使用eval函数。所以:num_array=eval(nums)也很好用!这更容易,但如果要使用eval,则需要彻底清除无效输入的数据。eval()打开了大量的安全漏洞,如果你不小心的话。在Rails 4中,你现在可以使用
数组
类型,它在PostgreSQL上以数组的形式存储,或者在其他任何东西上以字符串的形式存储。
# db/migrate/20140207133952_create_books.rb
create_table :books do |t|
  t.string 'title'
  t.string 'tags', array: true
  t.integer 'ratings', array: true
end
add_index :books, :tags, using: 'gin'
add_index :books, :ratings, using: 'gin'

# app/models/book.rb
class Book < ActiveRecord::Base
end

# Usage
Book.create title: "Brave New World",
            tags: ["fantasy", "fiction"],
            ratings: [4, 5]

## Books for a single tag
Book.where("'fantasy' = ANY (tags)")

## Books for multiple tags
Book.where("tags @> ARRAY[?]::varchar[]", ["fantasy", "fiction"])

## Books with 3 or more ratings
Book.where("array_length(ratings, 1) >= 3")