Ruby on rails 具有条件生成空键的Jbuilder
这是我的public.json.jbuilderRuby on rails 具有条件生成空键的Jbuilder,ruby-on-rails,json,Ruby On Rails,Json,这是我的public.json.jbuilder json.(@plantao, :data_referencia, :data_fim) json.plantoes_locais @plantao.plantao_lotacoes do |plantao_local| json.plantao_local(plantao_local, :periodo_inicio, :periodo_fim, :servidor, :lotacao, :contato ) if plan
json.(@plantao, :data_referencia, :data_fim)
json.plantoes_locais @plantao.plantao_lotacoes do |plantao_local|
json.plantao_local(plantao_local,
:periodo_inicio, :periodo_fim, :servidor, :lotacao, :contato
) if plantao_local.dentro_periodo?
end
当生成我的JSON时,由于我的条件错误,在文件末尾会生成几个空的{}
{
"data_referencia": "2014-12-15T18:00:00.000-02:00",
"data_fim": "2014-12-18T08:00:00.000-02:00",
"plantoes_locais": [
{
"plantao_local": {
"periodo_inicio": "2014-12-16T08:00:00.000-02:00",
"periodo_fim": "2014-12-17T08:00:00.000-02:00",
"servidor": null,
"lotacao": null,
"contato": null
}
},
{
"plantao_local": {
"periodo_inicio": "2014-12-16T08:00:00.000-02:00",
"periodo_fim": "2014-12-17T08:00:00.000-02:00",
"servidor": null,
"lotacao": null,
"contato": null
}
},
{},
{},
{},
{},
{},
{},
{},
{}
]
}
如何删除这些空{}?使用和删除空哈希。像这样的方法应该会奏效:
json.(@plantao, :data_referencia, :data_fim)
json.plantoes_locais @plantao.plantao_lotacoes do |plantao_local|
json.plantao_local(plantao_local,
:periodo_inicio, :periodo_fim, :servidor, :lotacao, :contato
) if plantao_local.dentro_periodo?
end.delete_if(&:empty?)
使用和删除空哈希。像这样的方法应该会奏效:
json.(@plantao, :data_referencia, :data_fim)
json.plantoes_locais @plantao.plantao_lotacoes do |plantao_local|
json.plantao_local(plantao_local,
:periodo_inicio, :periodo_fim, :servidor, :lotacao, :contato
) if plantao_local.dentro_periodo?
end.delete_if(&:empty?)
Jbuilder github页面显示您可以使用:
json.ignore_nil!
Jbuilder github页面上说您可以使用:
json.ignore_nil!