2013-10-22 30 views
1

现在我得到:如何在JBuilder中的默认返回空字符串,而不是“<null">

{"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 
+0

我不明白,并在那里我应该把这个方法? – tomekfranek

+0

就在你获得json数据之后。 – anand4tech

回答

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} 
+0

嗯,但我保持我的所有jbuilder视图在api/views/document.json.jbuilder文件中。 – tomekfranek

+0

你可以在你的视图中添加ruby代码。看看这里:http://stackoverflow.com/questions/14459750/render-a-jbuilder-view-in-html-view – Pol0nium

相关问题