Search code examples
ruby-on-railsjsonserializationrails-api

Rendering json data fields from mysql db in rails response object


I have a rails 4.2 app that uses mysql db 5.7 which supports json fields. So my user model has a field called display_pic which is a json object.

class User < ActiveRecord::Base
    serialize :display_pic, JSON
    ....

In the action get_user I render user as follows

def get_user
  @u = User.where(...)
  render json: { user: @u }
end

The problem is that the json field display_pic doesn't come out as a nested json object, rather it is rendered as a string. I would like to have a response like the following

{ 
  "user": {
     "name": "some name", 
     "email": "some email",
     "display_pic": {
         "url": "http://someurl.com",
         "width": "400px",
      }
   }
}

Solution

  • Probably a better way to do this, but you can format it as json in the serializer.

    class UserSerializer < ActiveModel::Serializer
      attribute :name
      attribute :email
      attribute :display_pic
    
      def display_pic
        JSON.parse(object.display_pic)
      end
    end