Prince Abalogu
Prince Abalogu

Reputation: 395

Json not looking pretty on nested query rails

heres my show action to display users

def show 
  manager = HiringManager.find(params[:id])
  candidates = manager.users.to_json(:include => [:experiences, :educations])
  render :json => { manager: manager, candidates: candidates }                   
end 

and my HiringManager and Hire Models

class HiringManager < ActiveRecord::Base
  has_many :hires
  has_many :users, through: :hires
end

class Hire < ApplicationRecord
  belongs_to :hiring_manager
  belongs_to :user
end

it works quite alright but the json preview is not pretty enter image description here

Upvotes: 0

Views: 41

Answers (1)

max
max

Reputation: 102240

No, it does not work alright. The problem is that you are double encoding the JSON. candidates = manager.users.to_json(:include => [:experiences, :educations]) creates a JSON string.

When you pass that to render json: its treated as a string and not an object and the quotes are escaped.

Instead of .to_json you want to use .as_json which creates an array of hashes instead of a string.

def show 
  manager = HiringManager.find(params[:id])
  candidates = manager.users.as_json(include: [:experiences, :educations])
  render json: { manager: manager, candidates: candidates }                   
end 

Upvotes: 1

Related Questions