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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With