我有一个 postgres 数据库,每一行代表一个“索引”(只是一个名称而不是关键字)。对于每个市场,都有一个属性“stats”,它是我从外部源放入数据库的二维数组。
create_table "indices", force: true do |t|
t.string "name", null: false
t.float "returns", default: [], array: true
t.float "navs", default: [], array: true
t.float "stats", default: [], array: true
t.string "updated_at"
t.string "created_at"
t.integer "idx_type_id"
end
我的问题是如何从数据库中获取统计值并将其输入到我的 Rails 程序中?
在控制台中,我尝试了以下代码:
a = Index.find(1)
a.name
a.stats
它正确地获取了 name 属性,但是我得到了 stats 属性的以下错误
undefined method `to_f' for ["0.259854651130407", "0.261425018884344"]:Array
方括号内显示的数字是二维数组第一行的值。有什么想法吗?
编辑:我正在运行 rails 4.0.1,这里是创建表的原始迁移。这里有语法错误吗?
class CreateIndices < ActiveRecord::Migration
def change
create_table :indices, {:id => false} do |t|
t.string :name
t.float :returns, array: true, default: []
t.float :navs, array: true, default: []
t.float :sharpe
t.timestamps
end
execute "ALTER TABLE indices ADD PRIMARY KEY (name);"
end
end
编辑 2:这是 psql 中以下查询的输出
查询:
select stats from indices where id < 3
输出:
stats
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------------------
{{0.259854651130407,0.261425018884344},{0.114409534648231,0.113829156756227},{2.27126744225792,2.28284789710692},{0.0562802038101342,0.0561701509132937},{4.61715902819129,4.65416265816855},{0.0
92128059492271,0.0921734852013666},{2.82058096699852,2.81919090465893},{0.0292770008925915,0.0291771074372238},{8.87572644765545,8.95993612275702}}
{{0.259854651130407,0.261425018884344},{0.114409534648231,0.113829156756227},{2.27126744225792,2.28284789710692},{0.0562802038101342,0.0561701509132937},{4.61715902819129,4.65416265816855},{0.0
92128059492271,0.0921734852013666},{2.82058096699852,2.81919090465893},{0.0292770008925915,0.0291771074372238},{8.87572644765545,8.95993612275702}}
(2 rows)
最佳答案
float类型的列不能存储数组,只能存储float。
您可以使列类型为 text
,然后通过 serialize :stats, Array
serialize
模型中的列,或者您可以创建通过添加列 :indices, :stats, :text, :array => true
。
但在您当前的状态下,您已告知数据库该列是 float
类型,而不是数组,因此 ORM 在读取/写入时会按原样处理数据。
关于ruby-on-rails - rails postgres 从数据库中读取数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20668251/