Member-only story
JSON Serialized Columns with Rails
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