regedarek regedarek - 7 months ago 51
Ruby Question

How to returns empty string instead of null in jbuilder views?

I have simple jbuilder view

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


When
pharmaceutic.dosage => nil


My rendered json looks like below:

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


I would like set up for all jBuilder views that when some attribute is
nil
it should be rendered as empty string.

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


How to achieve that?

Answer

nil.to_s #=> "" so, you can simply add .to_s

json.id pharmaceutic.id
json.name pharmaceutic.name.to_s
json.dosage pharmaceutic.dosage.name.to_s
Comments