简体   繁体   中英

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 在此处输入图片说明

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM