So you need to store some JSON blobs in your database. What do you do? You have plenty of options these days. You can serialize a hash into the database. You can reach for a document store like mongodb. Or, you can lean on rails 4 postgres json data type support.
If you haven't yet upgraded to rails 4, go ahead and do that now, I'll wait...
tick, tock, looks at watch
Jokes aside, it's totally worth it.
Anywho, now that we are on rails 4, let's go ahead and stuff some JSON into the database.
You might do that using something like this:
draft = CollectionDraft.find(params[:id])
draft.content = { foo: 'bar', baz: 'qux' }
draft.save
stuff
# We want to prevent loading the json content column into
# a ruby hash just to be converted to JSON right away.
#
# Hopefully this won't be necessary as rails pg json support matures
#
class RawJsonEmitter
attr_reader :raw_json
def initialize(thing)
@raw_json = thing.content_before_type_cast || "{}"
end
# Basically opting out of as_json behavior
#
def as_json(*args)
self
end
def encode_json(encoder)
raw_json
end
end