ActiveModel :: Serializer:将ids转换为字符串

时间:2016-06-07 14:09:18

标签: ruby-on-rails json serialization

当我将模型对象序列化为JSON时,我想将所有ID转换为字符串,因为它们应该是JavaScript中的“后框”值,而不是双精度浮点数。有没有办法告诉ActiveModel::Serializer通过.to_s运行所有ID(如果不是零)?

我已经尝试创建一个BaseSerializer类,用于定义所有其他序列化程序继承的自定义id方法。此方法会对字符串进行适当的转换,但不会调用它。 belongs_to关系,只显示ID(因为JSON嵌套深度截止)。

1 个答案:

答案 0 :(得分:0)

请试试这个......

我有一个像这样的序列化器

class ResumesSerializer < ActiveModel::Serializer
  attributes :first_name, :last_name, :age

  def age
    object.talent.age.to_s if object.talent.age.present? 
  end
end
相关问题