我如何能坚持一个数组在Ruby on Rails的数据库? [英] How can I persist an array to the database in Ruby on Rails?
问题描述
我想在Rails中坚持阵列我SQLite数据库的Array。
I'm trying to persist an Array of Arrays to my SQLite database in Rails.
现在,我已经有了一个对象,可容纳这样的一个数组和实例似乎保存没有问题。但是,它显然不被保存到当我的看法比上创建数组一个不同的呼吁My_Object.array功能的数据库 - ,它出来零并不起作用。
Right now, I've got an object that can hold such an Array, and instances appear to save with no problem. However, it's clearly not being persisted to the database-- when I call functions on My_Object.array in views different than the one that the array is created on, it comes out nil and doesn't work.
例如:
class My_Object < ActiveRecord::Base
attr_accessor :array
end
当我称之为 My_Object.new(:数组=&GT; [1,2,3],[4,5,6])
,一切似乎正常工作,但我不能访问:其他地方阵列
属性,它只是证明无
When I call My_Object.new(:array => [ [1, 2, 3], [4, 5, 6] ])
, everything appears to work properly, but I can't access the :array
property anywhere else, it just turns out nil.
任何想法?
推荐答案
首先创建阵列
您的表称为文本列。然后使用<一个href=\"http://api.rubyonrails.org/classes/ActiveRecord/Base.html#label-Saving+arrays,+hashes,+and+other+non-mappable+objects+in+text+columns\"><$c$c>serialize$c$c>:
First create a text column called array
in your table. Then use serialize
:
class My_Object < ActiveRecord::Base
serialize :array
end
这会自动使用YAML并自动解压缩它,当你把它背出来的数据库的序列化阵列。
That will automatically serialize your array using YAML and automatically unpack it when you pull it back out of the database.
您应该重新考虑,虽然你的设计。你将无法做任何与数据库内,特别是序列化的数据在所有的,你就无法在查询中使用它。该YAML将只是一个不透明的blob的进入数据库,并回来了,该数据库将无法做任何事情都要用它。如果你是某个数据库将永远需要寻找数组中
然后继续使用连载
,否则你马上要建立额外的表格来存储阵列的数据。
You should reconsider your design though. You won't be able to do anything at all with the serialized data inside the database and in particular, you won't be able to use it in queries. The YAML will be just an opaque blob that goes into the database and comes back out, the database won't be able to do anything else with it. If you're certain that the database will never need to look inside array
then go ahead and use serialize
, otherwise you'll want to set up extra tables to store your array data.
这篇关于我如何能坚持一个数组在Ruby on Rails的数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!