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?
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.
. 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.
Unlike other programming languages like Java, Ruby only has dynamic arrays but no static arrays.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With