Array of Hashes with ActiveRecord

一个人想着一个人 提交于 2019-12-20 02:48:08

问题


ActiveRecord (Rails 4.0) supports PostgreSQL Hstore and Array datatypes, so an Array of Hashes is theoretically possible, but my implementation throws:

PG::InvalidTextRepresentation: ERROR:  malformed array literal:

The error is obvious (double quote conflict):

"{"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"

The solution is not obvious to me, how can I implement this?

My schema:

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

My seed:

@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:


This is a confirmed bug in Rails that was fixed in commit 7c32db1, which is present in versions 4.1.0.rc1 and later.



来源:https://stackoverflow.com/questions/22596826/array-of-hashes-with-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!