【问题标题】:Json not looking pretty on nested query railsJson 在嵌套查询轨道上看起来不漂亮
【发布时间】:2019-05-15 20:29:15
【问题描述】:

这是我显示用户的显示操作

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

还有我的 HiringManager 和 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

它工作得很好,但 json 预览并不漂亮

【问题讨论】:

    标签: ruby-on-rails json activerecord


    【解决方案1】:

    不,它不能正常工作。问题是您对 JSON 进行双重编码。 candidates = manager.users.to_json(:include =&gt; [:experiences, :educations]) 创建一个 JSON 字符串。

    当您将其传递给 render json: 时,它被视为字符串而不是对象,并且引号被转义。

    您想使用 .as_json 而不是 .to_json,它会创建一个哈希数组而不是字符串。

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

    【讨论】:

      猜你喜欢
      • 2020-06-20
      • 2021-10-25
      • 2013-11-17
      • 1970-01-01
      • 1970-01-01
      • 2014-06-26
      • 2015-11-16
      • 1970-01-01
      相关资源
      最近更新 更多