Error trying to create an array of json objects in Rails 4 using PostgreSQL

I am trying to add an array of json objects to one of my models. Starting migration works fine if I do not enable the default value, but trying to save any value will fail. When you try to use an empty array as the default value, the same error occurs when performing the migration.

My migration:

class AddJsonExampleToMyModel < ActiveRecord::Migration
  def change
    add_column :my_models, 
               :json_example
               :json,
               array: true,
               default: []
  end
end

The error looks like this:

PG::InvalidTextRepresentation: ERROR:  malformed array literal: "[]"
DETAIL:  "[" must introduce explicitly-specified array dimensions.
: ALTER TABLE "my_models" ADD COLUMN "json_example" json[] DEFAULT   '[]'/.../db/migrate/20151013125334_add_json_example_to_my_model.rb:3:in     `change'
ActiveRecord::StatementInvalid: PG::InvalidTextRepresentation: ERROR: malformed array literal: "[]"
DETAIL:  "[" must introduce explicitly-specified array dimensions.
: ALTER TABLE "my_models" ADD COLUMN "json_example" json[] DEFAULT '[]'
/.../db/migrate/20151013125334_add_json_example_to_my_model.rb:3:in`change'
PG::InvalidTextRepresentation: ERROR:  malformed array literal: "[]"
DETAIL:  "[" must introduce explicitly-specified array dimensions.

Am I trying to do something that cannot be done, or am I doing it wrong?

My setup: Rails 4.1.9, (PostgreSQL) 9.4.4, Ruby 2.1.0p0

+4
source share
1 answer

Rails JSON, Postgres , JSON. Postgres JSON, , , . Rails 4.1.9 .

Ruby 2.1.0p0, Rails 4.1.9, Postgres 9.4.4:

add_column :things, :data, :json, default: []
> t = Thing.new
 => #<Thing id: nil, data: []>
> t.data = [{a: 1}]
 => [{:a=>1}]
> t.save
   (0.2ms)  BEGIN
  SQL (0.7ms)  INSERT INTO "things" ("data") VALUES ($1) RETURNING "id"  [["data", "[{\"a\":1}]"]]
   (0.5ms)  COMMIT
 => true
> Thing.first
  Thing Load (1.0ms)  SELECT  "things".* FROM "things"   ORDER BY "things"."id" ASC LIMIT 1
 => #<Thing id: 1, data: [{"a"=>1}]>

, Rails , . , . :

> t = Thing.create
   (0.2ms)  BEGIN
  SQL (0.4ms)  INSERT INTO "things" DEFAULT VALUES RETURNING "id"
   (4.7ms)  COMMIT
 => #<Thing id: 2, data: []>
> t.data << 1
 => [1]
> t.save
   (0.2ms)  BEGIN
   (0.2ms)  COMMIT
 => true
> t.reload.data
  Thing Load (0.3ms)  SELECT  "things".* FROM "things"  WHERE "things"."id" = $1 LIMIT 1  [["id", 2]]
 => []

save , , , . , , *_will_change! Rails, .

> t.data << 1
 => [1]
> t.data_will_change!
 => [1]
> t.save
   (0.2ms)  BEGIN
  SQL (0.4ms)  UPDATE "things" SET "data" = $1 WHERE "things"."id" = 2  [["data", "[1]"]]
   (0.4ms)  COMMIT
 => true
> t.reload.data
  Thing Load (0.4ms)  SELECT  "things".* FROM "things"  WHERE "things"."id" = $1 LIMIT 1  [["id", 2]]
 => [1]
+4

Source: https://habr.com/ru/post/1611450/


All Articles