5

我有简单的 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":""}

如何做到这一点?

4

3 回答 3

6

nil.to_s #=> ""所以,你可以简单地添加.to_s

json.id pharmaceutic.id
json.name pharmaceutic.name.to_s
json.dosage pharmaceutic.dosage.name.to_s
于 2013-08-01T14:03:53.467 回答
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
于 2015-04-01T10:35:10.973 回答
0

json.dosage pharmaceutic.dosage.name.to_s

如果 pharmaceutic 为 nil,这将不起作用。你可以简单地做

json.dosage pharmaceutic.dosage.name unless pharmaceutic.dosage.nil?
于 2016-04-18T09:51:28.417 回答