5

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?

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

6 Comments

The actual application will be using this array almost exclusively... I'm just trying to implement conway's game of life into a rails app, using a Game object to hold the initial array-- This array is basically all that will be used in the entire application, as the whole point is to run it through the algorithm to get new points. Is this even possible using serialize? Should I just rework the entire program?
@Benjamin: serialize should be fine for something like that.
Just a minor point: You can use serialize :array, Array if you want to enforce an Array.
@Swanand: Thanks, that is worth mentioning.
@Benjamin: Just serialize :array should be sufficient. You can say serialize :array, Array if you want to be explicit but I don't think there is a way to say "array or arrays" with serialize.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.