使用ActiveRecord的哈希数组

时间:2014-03-23 20:45:05

标签: ruby-on-rails postgresql activerecord

ActiveRecord(Rails 4.0)支持PostgreSQL Hstore和Array数据类型,因此理论上可以使用Hashes数组,但我的实现会抛出:

PG::InvalidTextRepresentation: ERROR:  malformed array literal:

错误很明显(双引号冲突):

"{"null"=>"false","name"=>"schema_id","type"=>"integer","null"=>"false","name"=>"title","type"=>"text"}"

: INSERT INTO "entities" ("attribute_hash", "schema_id", "title") VALUES ($1, $2, $3) RETURNING "id"

解决方案对我来说并不明显,我该如何实现?

我的架构:

create_table :schemas do |t|
  t.text    :title
  t.timestamps
end

create_table :entities do |t|
  t.integer :schema_id,       null: false
  t.text    :title,           null: false
  t.hstore  :attribute_hash, array: true
end

我的种子:

@schema_id = Schema.create!(title: 'accreu')
Entity.create!(
  schema_id: @schema_id.id, title: 'entities',
  attribute_hash: [
    {null: "false", name: :schema_id, type: :integer},
    {null: "false", name: :title, type: :text}
   ]
)

1 个答案:

答案 0 :(得分:3)

这是Rails中已确认的错误,已在提交7c32db1中修复,该版本存在于4.1.0.rc1及更高版本中。