Skip to content

Instantly share code, notes, and snippets.

@tonywok
Last active October 13, 2015 23:13
Show Gist options
  • Select an option

  • Save tonywok/8838149 to your computer and use it in GitHub Desktop.

Select an option

Save tonywok/8838149 to your computer and use it in GitHub Desktop.
render raw json rails4/postgresql

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

https://github.com/rails/rails/blob/4-0-stable/activesupport/lib/active_support/json/encoding.rb#L266

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment