如何在jbuilder中返回空字符串而不是“<null”>作为默认值?</null“>

时间:2013-10-22 10:22:20

标签: ruby-on-rails ruby json jbuilder

现在我得到:

{"id":1,"name":"HerzASS ratiopharm","dosage":null}

我想返回""而不是null

但是默认。如何实现这一目标。我不想为我的应用程序中的每个属性添加m.dosage || ""

我在views/api/documents/_document.json.jbuilder

中保留我的jbuilder观看次数
json.id document.id
json.category document.category # sometimes this is nil
json.note document.note
json.attachments document.attachments do |attachment|
  json.url URI.join(request.url, attachment.url).to_s
end
json.created_at document.created_at
json.updated_at document.updated_at

1 个答案:

答案 0 :(得分:0)

这是你在找什么?

def replace_null(yourhash)
  yourhash.each do |k,v|
    if v == nil then
      yourhash[k] = ""
    end
  end
end

yourhash.each{|k,v| a[k] = "" if v == nil}