0

I'm doing a rails application for a school project, and now i need store a matrix using postgresql. I was saving the values in an array, but i thought better and concluded that i need a matrix, but i don't know how to do this.

I tried in this way: - Migration:

add_column :table, :field, :text, array:true, default: []

Using this migration, the values are saving like:

[a,b,c,d,a,c,b,d,a,b,c,d,e]

I think what i need is like this:

[[a,b,c,d],[a,c,b,d],[a,b,c,d,e],[...]].

Because in this way the values are grouped.

Can someone help me?

3

1 Answer 1

0

I made simple rails project to show you how to save multidimensional array to DB. Please check it here: https://github.com/nezirz/multidimensional_arrays

How it looks:

enter image description here

Here is super tutorial with informations you need. Please check this tutorial. This is a footer rule info about your case with multidimensional arrays:

One last note about arrays in PostgreSQL: there are no element count constraints, and any array can be multidimensional. With the multidimensional arrays, they must be “square” (the sub arrays must all have the same number of elements).

[[1,2,3], [2,3,4], [4,5,nil]]
# Valid array value in PostgreSQL, each subarray has the same number of
# elements
[1,2,[3,4]]
# Invalid array, we are mixing values and arrays at a single level

Please try this tutorial https://dockyard.com/blog/ruby/2012/09/18/rails-4-sneak-peek-postgresql-array-support

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.