[英]Rails active model serializer, how to return empty string instead of null
我必须使用遗留应用程序,并且必须重写旧的(PHP基础)rest api。 在旧的api中,当属性为null时,它变为空字符串。
然而,Rails只返回一个null,这会破坏应用程序。 重写应用程序不是解决方案(即使这是最干净的方式)。 同样在旧的api中,其他值是(整数,布尔值,数字)的字符串。 所以我想知道,如何在每个属性上执行to_s,而不是覆盖每个属性。 我正在使用主动模型序列化器。
一点点元编程应该有所帮助:
class MySerializer < ActiveModel::Serializer
[:id, :attr1, :attr2, :attr2].each do |attr|
# Tell serializer its an attribute
attribute attr
# Define a method with the same name as the attribute that calls the
# underlying object and to_s on the result
define_method attr do
object.send(attr).to_s
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.