【问题标题】:How to return empty strings instead of "<null"> in jbuilder as default?如何在jbuilder中默认返回空字符串而不是“<null”>?
【发布时间】:2013-10-31 03:54:02
【问题描述】:

现在我明白了:

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

我想返回 "" 而不是 null

但默认情况下。如何实现。我不想为我的应用程序中的每个属性添加m.dosage || ""

我将我的 jbuilder 视图保存在 views/api/documents/_document.json.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

【问题讨论】:

  • 我不明白,我应该把这个方法放在哪里?
  • 在你得到 json 数据之后。

标签: ruby-on-rails ruby json jbuilder


【解决方案1】:

这就是你要找的吗?

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}

【讨论】:

  • 嗯,但我将所有 jbuilder 视图保存在 api/views/document.json.jbuilder 文件中。
  • 您可以将 ruby​​ 代码放在您的视图中。看看这里:stackoverflow.com/questions/14459750/…
猜你喜欢
  • 2013-08-02
  • 1970-01-01
  • 2015-01-31
  • 2011-03-29
  • 1970-01-01
  • 2014-07-28
  • 2012-12-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多