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

Nik*_*arg 23 ruby activerecord ruby-on-rails

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

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

Mik*_*use 35

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

serialize记录在Rails/ActiveRecord API中(向下滚动到"在文本列中保存数组,散列和其他不可映射的对象"一节)

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

格式化输出:

delim = ',' # or ' ' for spaces, or whatever you choose
array.join(delim)
Run Code Online (Sandbox Code Playgroud)

转换回数组可能会如下工作:

num_array = nums.split(delim).map(&:to_i) # or to_f if not integers
Run Code Online (Sandbox Code Playgroud)

或者也许使用String#scan?

num_array = nums.scan(/\d+/).map(&:to_i) # for positive integers
Run Code Online (Sandbox Code Playgroud)

  • 它更容易,但是如果您要使用eval,则需要非常彻底地清除无效输入的数据.如果你不小心,eval()会打开很多安全漏洞. (3认同)

Ste*_*gán 15

如果你正在使用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")
Run Code Online (Sandbox Code Playgroud)

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