使用ActiveRecord在数据库中存储数组

我在rails 2.3.8&我使用mysql作为db适配器。 我想在我的数据库中存储数组。 在搜索之后,我可以拿出这篇非常有用的文章 。

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

如果您使用serialize那么您不必担心数据如何存储在文本字段中,尽管它实际上是YAML。

在Rails / ActiveRecord API中记录了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 

或者也许使用String#scan?

 num_array = nums.scan(/\d+/).map(&:to_i) # for positive 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") 

http://edgeguides.rubyonrails.org/active_record_postgresql.html