0

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",
      }
   }
}

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Probably the best solution, however, a quicker solution turned out to be just overriding as_json. thanks a lot for the answer :)
Maybe you should use both solution overriding as_json with super(options.merge(methods: [:display_pic])
0

Use the following code it will solve your problem:

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

Comments

0

Have you tried to use the method .as_json ?

def get_user
  @u = User.where(...)
  render json: @u.as_json
end

You should have not need to set serialize :display_pic, :JSON, but you can overload the method in your user.rb class in order to get on response references or methods results authomatically loaded on your front end:

class PlayerCharacter < ApplicationRecord

      [...]
      def as_json(options = {})
        super(options.merge(include: [ :reference1, :reference2]).merge(methods: [:method_name1, :method_name2])
      end
end

EDIT: you could add display_pic as follow:

class PlayerCharacter < ApplicationRecord

      [...]
      def as_json(options = {})
        super(options.merge(include: [ :display_pic])
      end
end

1 Comment

include: [:display_pic] does not do the job. however, I liked the idea of dealing with it in as_json. def as_json(options = {}) h = super(options) h[:display_pic] = JSON.parse(display_pic) h end This did the job. Thanks for the answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.