wurde
wurde

Reputation: 2627

Array of Hashes with ActiveRecord

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}
   ]
)

Upvotes: 3

Views: 968

Answers (1)

Luke
Luke

Reputation: 4925

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

Upvotes: 3

Related Questions