如何在jbuilder视图中返回空字符串而不是null?

时间:2013-08-01 13:46:45

标签: ruby-on-rails ruby json jbuilder

我有简单的jbuilder视图

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":""}

如何实现?

3 个答案:

答案 0 :(得分:5)

nil.to_s #=> ""因此,您只需添加.to_s

即可
json.id pharmaceutic.id
json.name pharmaceutic.name.to_s
json.dosage pharmaceutic.dosage.name.to_s

答案 1 :(得分: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

答案 2 :(得分:0)

  

json.dosage pharmaceuticalic.dosage.name.to_s

如果药物为零,这将无效。你可以简单地做到

json.dosage pharmaceutic.dosage.name unless pharmaceutic.dosage.nil?
相关问题