2010-06-23 61 views
23

我在rails上2.3.8 &我正在使用mysql作为db适配器。 我想将数组存储在我的数据库中。搜索后,我可以拿出这个非常有用的article使用ActiveRecord将数组存储在数据库中

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

+0

在Rails 4,你现在可以使用'array'类型,将其存储为PostgreSQL的数组,或作为其他一切的字符串。 – Zaz 2014-07-30 18:55:10

回答

35

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

serializethe Rails/ActiveRecord API文件(向下滚动到标题为“保存数组,散列和其他非可映射在文本列对象”一节)

对于显示器,你需要的格式,是可以理解的用户和可以轻松地将其转换回代码中的数组。逗号或空格分隔?

格式输出:

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

或者是使用字符串#扫描:

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

转换回一个数组如下可能会奏效?

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

谢谢迈克。 :) 我已经想通了。 一个更容易(虽然容易出错)的方式是直接使用eval函数。 so: num_array = eval(nums)工作也很甜蜜! – 2010-06-26 12:11:20

+3

这很容易,但如果您要使用eval,则需要彻底清理无效输入的数据。如果你不小心,eval()会打开大量的安全漏洞。 – MunkiPhD 2013-09-06 02:10:23

13

如果您使用的是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

相关问题