Code Ramblin's

Postgres JSON Column Type in Rails 4

October 29, 2015

In recent days I have been starting a new project using Rails of course and hit a unique issue. I was needing to store arbitrary data with each record, that would likely be different for each record. I thought about using MongoDB for this project but didn’t feel that it was necessary since Postgres is always adding awesome new features.

At first glance ,and Google search, I thought about using the hstore extension. However, this stores all values as strings and I needed to store all different types of data. Enter JSON, we all love JSON so why not store it in the database? Using JSON with Postgres doesn’t even require an extension and is supported out of the box with Rails 4+. Just use the json column type in your migration when creating or modifying tables. You can now store all sorts of complex data types as long as it is valid json.

class User < ActiveRecord::Base
#let's say our json column is named settings
me = User.create(name: 'Chad', settings: {notifications: [{email: true, sms:false}], profile_color: '#ccc'})

This will save the json as you provide it, most importantly keeping the values as the same data type. Now when you retrieve the User’s settings from the you will be able to use all of the corresponding enumerable methods on them.

me.settings.each_key { |key| puts me.settings[key] }
#Outputs {"email"=>true, "sms"=>false} #ccc

I’m curious about some interesting uses you have found for the json column type, let me know about them in the comments.