如何在Ruby on Rails中将数组持久化到数据库? [英] How can I persist an array to the database in Ruby on Rails?

查看:116
本文介绍了如何在Ruby on Rails中将数组持久化到数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



现在,我有一个可以容纳这样一个数组的对象,并且实例看起来保存没有问题。然而,它显然不是被持久化到数据库 - 当我调用My_Object.array中的函数的视图不同于数组被创建的视图,它出来nil,不工作。



例如:

  class My_Object< ActiveRecord :: Base 
attr_accessor:array
end

c $ c> My_Object.new(:array => [[1,2,3],[4,5,6]]),一切似乎工作正常,在任何地方访问:array 属性,它只会变成nil。



任何想法?

解决方案

首先在表中创建一个名为 array 的文本列。然后使用 serialize

  class My_Object< ActiveRecord :: Base 
serialize:array
end

数组使用YAML,并且当你将它从数据库中取出时自动解包。



你应该重新考虑你的设计。您将无法对数据库中的序列化数据执行任何操作,特别是,您将无法在查询中使用它。 YAML将只是一个不透明的blob进入数据库并回来,数据库将无法做任何其他与它。如果你确定数据库永远不需要在数组里面,然后使用 serialize ,否则你将需要设置额外的表来存储您的数组数据。


I'm trying to persist an Array of Arrays to my SQLite database in Rails.

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.

For example:

class My_Object < ActiveRecord::Base
  attr_accessor :array
end

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.

Any ideas?

解决方案

First create a text column called array in your table. Then use serialize:

class My_Object < ActiveRecord::Base
  serialize :array
end

That will automatically serialize your array using YAML and automatically unpack it when you pull it back out of the database.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆