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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3100427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:49:09  来源:igfitidea点击:

Storing arrays in database using ActiveRecord

ruby-on-railsrubyactiverecord

提问by Nikhil Garg

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.

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

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 ?

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

回答by Mike Woodhouse

If you use serializethen you shouldn't have to worry about how the data is stored within the text field, although it's actually YAML.

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

serializeis documented in the Rails/ActiveRecord API(scroll down to the section headed "Saving arrays, hashes, and other non-mappable objects in text columns")

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

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?

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

Formatting for output:

输出格式:

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

or perhaps using String#scan?

或者也许使用 String#scan?

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

回答by Steven Barragán

If you're using postgres and rails 4, now you have a better native option.

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

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