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
arrayin your table. Then useserialize: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
arraythen go ahead and useserialize, otherwise you’ll want to set up extra tables to store your array data.