Error when modifying Postgres JSON field in Rails 3.2
I am trying to use a JSON field type (Postgres 9.3, not JSONB) in a Rails 3.2 application.
I created a field with the following migration with no problem:
def change
add_column :blocks, :meta, :json
end
However, when I try to change the field like this:
b.meta = {name: "John"}
b.save
I am 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 the JSON type is supported in Rails 3.2, but I've seen some posts talk about it ASAP (although there are no details on how it works).
source to share
I think you are correct that ActiveRecord in Rails 3 does not support JSON. The reason for your error is that given a complex data type (in this case Hash), ActiveRecord serializes it to a string first, and the default serialization is YAML. This is what ---
in your error message is 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
It will get tiresome quickly. Instead, you can tell ActiveRecord to use JSON instead of YAML when serializing this attribute:
class Block < ActiveRecord::Base
serialize :meta, JSON
end
source to share