【问题标题】:storing multidimensional array(matrix) rails postgresql存储多维数组(矩阵)rails postgresql
【发布时间】:2018-10-02 18:20:59
【问题描述】:

我正在为一个学校项目做一个 Rails 应用程序,现在我需要使用 postgresql 存储一个matrix。我将值保存在一个数组中,但我想得更好,并得出结论我需要一个矩阵,但我不知道该怎么做。

我试过这样: - 迁移:

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

使用此迁移,值保存如下:

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

我想我需要的是这样的:

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

因为以这种方式将值分组。

有人可以帮我吗?

【问题讨论】:

标签: ruby-on-rails postgresql ruby-on-rails-5


【解决方案1】:

我制作了一个简单的 rails 项目来向您展示如何将多维数组保存到 DB。请在此处查看:https://github.com/nezirz/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

请试试这个教程https://dockyard.com/blog/ruby/2012/09/18/rails-4-sneak-peek-postgresql-array-support

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    相关资源
    最近更新 更多