Member-only story

JSON Serialized Columns with Rails

Usama Ashraf
codeburst
Published in
3 min readMar 12, 2018

Ever since the NoSQL boom, there were unnecessary jumps made to embrace Mongo, Cassandra etc as primary datastores for applications that probably would’ve been fine with an RDBMS instead. I think these digressions were in part fashionable consumption. But there was also a legitimate need for an unstructured solution to specific problems, like storing user settings, API responses, change logs, health records etc. JSON columns in MySQL, Postgres etc can solve these problems while staying within the relational paradigm.

Rails makes them a breeze to work with:

# Migration for adding a JSON column to the users table.
def change
add_column :users, :facebook_profile_data, :json
end
# user.rb
class User < ApplicationRecord
#...
serialize :facebook_profile_data, JSON
end

Now you can simply do:

user = User.create!({
username: 'usama.ashraf',
facebook_profile_data: {
object_id: '...',
profile_image_url: '...'
}
})
user.facebook_profile_data
# {'object_id' => '...', 'profile_image_url' => '...'}
user.facebook_profile_data['profile_image_url']user.facebook_profile_data['object_id'] = 'new-object-id'
user.save

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Usama Ashraf

Node.js, Rails, Python, C++, React enthusiast. Databases, architecture.

Responses (5)

What are your thoughts?

Really nifty, thanks! One thing I changed was nesting the class inside my model since I felt like they were tightly coupled and should be colocated.

Hi. I would like to ask how to implement this on GraphQL. I got problem on using enumerators from this.