ruby-on-rails - Rails 控制器渲染 json。我需要包含 nil 值
问题描述
我的 Rails 应用程序中有以下模型。
- 租
- 财产
- 接触
- 地址
class Lease < ApplicationRecord belongs_to :estate belongs_to :contact end class Contact < ApplicationRecord has_one :address end
lease.as_json(include: [:estate, {contact: {:include => :address}} ])
这contact.address
是不为空时生成的json:
{
id: 1,
start_date: "2019-05-09",
end_date: "2019-05-09",
title: "test title",
description: "test desc",
estate_id: 10,
contact_id: 4,
estate: {
id: 10,
address: "Address here",
lat: 37.0322021,
lng: 22.11332570000002,
},
contact: {
id: 1,
full_name: "contact name goes here",
address: {
title: 'this is the address'
}
}
}
我需要的是不要在json为空时隐藏“地址”字段(这是默认过程)。
换句话说,当contact.address
为 nil 时,我需要以下 json 结果:
{
id: 1,
start_date: "2019-05-09",
end_date: "2019-05-09",
title: "test title",
description: "test desc",
estate_id: 10,
contact_id: 4,
estate: {
id: 10,
address: "Address here",
lat: 37.0322021,
lng: 22.11332570000002,
},
contact: {
id: 1,
full_name: "contact name goes here",
address: {
title: ''
}
}
}
请注意,我需要有地址字段,但没有任何值。
解决方案
这并不是一个nil
像标准属性那样的真正值。联系 has_one 地址,因此数据库中需要有一条记录,或者如果您要使用as_json
.
对于如何解决这个问题,我有两个想法,但首先我对你的这部分数据感到有点惊讶:
contact: {
id: 1,
full_name: "contact name goes here",
address: {
title: 'this is the address'
}
}
}
我不确定这是否是您问题的根源,但您确定您没有手动编写代码吗?我希望出现 address.id :
contact: {
id: 1,
full_name: "contact name goes here",
address: {
id: 1,
title: 'this is the address'
}
}
}
我的第一个建议是
lease.contact.address = Address.new unless lease.contact.address
这可能会得到你想要的,但我还没有测试过。
我的第二个建议是考虑使用正式的序列化程序在活动模型记录和 JSON 之间获得另一层逻辑和处理。您可以定义在方法中计算的“属性”。
推荐阅读
- python-3.x - 如何传递/读取 PIL.JpegImagePlugin.JpegImageFile 对象?
- memory - 给定的是物理地址。段的开始地址是什么?x86
- python - 从oddsportal 网站抓取赔率
- java - 加载 fxml 文档后无法执行控制器方法
- swift - SwiftUI 未在子视图中更新 ObservedObject
- vba - 使当前选定记录的文本框消失
- azure-logic-apps - 如何在 Liquid 模板中获取 xml 属性值 - XML to JSON Liquid
- java - 有没有办法让 Java 语言服务器在 VSCode 中启动时跳过检查 `node_modules` 文件?
- node.js - 在 Docker 容器中执行 shell 脚本时的 ENONENT
- java - Springboot默认data.sql在启动时未加载