2013-10-22 29 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

相關問題