2013-08-01 55 views
5

我有簡單的JBuilder視圖如何在jbuilder視圖中返回空字符串而不是null?

json.id pharmaceutic.id 
json.name pharmaceutic.name 
json.dosage pharmaceutic.dosage.name 

pharmaceutic.dosage => nil

我的渲​​染JSON看起來象下面這樣:

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

我想設置爲所有JBuilder的意見,當某些屬性是nil它應該呈現爲空字符串。

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

如何做到這一點?

+1

也許這樣做? 'json.dosage pharmaceutic.dosage.name || 「」''這個操作數如果'dose.name'是'nil'它將使用空字符串 – MrYoshiji

回答

5

nil.to_s #=> ""所以,你可以簡單地添加.to_s

json.id pharmaceutic.id 
json.name pharmaceutic.name.to_s 
json.dosage pharmaceutic.dosage.name.to_s 
+8

這是一個很好的解決方案,但我正在尋找一個答案,我不需要廣告''to_s''爲我所有的500屬性。 – tomekfranek

0

要延長接受的答案,這裏有一個簡單的代理類來做到這一點:

class Proxy 

    def initialize(object) 
    @object = object 
    end 

    def method_missing method, *args, &block 
    if @object.respond_to? method 
     @object.send(method, *args, &block).to_s 
    else 
     super method, *args, &block 
    end 
    end 

    def respond_to? method, private = false 
    super(method, private) || @object.respond_to?(method, private) 
    end 

end 

class Roko < Struct.new(:a, :b, :c) 
end 

# instantiate the proxy instance by giving it the reference to the object in which you don't want nils 
roko = Proxy.new(Roko.new) 

puts roko.a.class # returns String even though :a is uninitialized 
puts roko.a  # returns blank 
0

json.dosage藥用。 dose.name.to_s

這是行不通的製藥是零。你可以簡單地做

json.dosage pharmaceutic.dosage.name unless pharmaceutic.dosage.nil? 
相關問題