Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I persist an array to the database in Ruby on Rails?

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?

like image 619
Benjamin Kovach Avatar asked Jan 25 '12 05:01

Benjamin Kovach


People also ask

How do you store an array in a database?

The easiest way store array type data in MySQL is to use the JSON data type. The JSON data type was first added in MySQL version 5.7. 8, and you can use the type for storing JSON arrays and objects. Let's see an example of using JSON type in MySQL.

What does .save do in Ruby?

. save is an “Instance Method”, it returns either true or false depending on whether the object was saved successfully to the database or not. If the model is new, a record gets created in the database, otherwise the existing record gets updated.

Are arrays in Ruby dynamic?

Unlike other programming languages like Java, Ruby only has dynamic arrays but no static arrays.

How do you add a value to an array in Ruby on Rails?

Ruby | Array append() function Array#append() is an Array class method which add elements at the end of the array. Parameter: – Arrays for adding elements. Return: Array after adding the elements at the end.


1 Answers

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.

like image 114
mu is too short Avatar answered Nov 15 '22 04:11

mu is too short