Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when modifying Postgres JSON field in Rails 3.2

I'm trying to use the JSON (Postgres 9.3, so not JSONB) field type in my Rails 3.2 application.

I've created the field with the following migration without a problem:

def change
  add_column :blocks, :meta, :json
end

However, when I'm trying to modify the field like this:

b.meta = {name: "John"}
b.save

I'm getting the following error:

ActiveRecord::StatementInvalid: PGError: ERROR:  invalid input syntax for type json
LINE 1: UPDATE "blocks" SET "meta" = '---

I'm not even sure if JSON type is supported in Rails 3.2 but I've seen some posts talking about it as possible (though no details on how it works).

like image 899
Filip Kis Avatar asked Sep 11 '25 20:09

Filip Kis


1 Answers

I think that you're correct that ActiveRecord in Rails 3 doesn't natively support JSON. The cause of your error is that given a complex data type (in this case a Hash), ActiveRecord will first serialize it to a string, and the default serialization is YAML. That's what the --- in your error message is from—it's the YAML header.

A quick solution is to convert the Hash to JSON before assigning it to your attribute:

hsh = { name: "John" }
b.meta = hsh.to_json
b.save

This will get tedious fast, though. Instead, you can tell ActiveRecord to use JSON instead of YAML when serializing this attribute:

class Block < ActiveRecord::Base
  serialize :meta, JSON
end
like image 82
Jordan Running Avatar answered Sep 14 '25 10:09

Jordan Running