首页 > 解决方案 > 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: ''
           }
        }
    }

请注意,我需要有地址字段,但没有任何值。

标签: ruby-on-railsjson

解决方案


这并不是一个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 之间获得另一层逻辑和处理。您可以定义在方法中计算的“属性”。

我使用fast_jsonapi取得了不错的成绩


推荐阅读