ActiveModel::Serializer in Rails - serializer methods ignored in JSON result

好久不见. 提交于 2019-12-13 14:13:44

问题


I am using active_model_serializers to create JSON for my Rails models.

serializer

class OptionSerializer < ActiveModel::Serializer
  self.root = false

  attributes :id

  def test_id
    object.id
  end
end

However, the to_json option seems to ignore the method added in OptionSerializer:

OptionSerializer.new(Option.find(13)).to_json.html_safe

expected output

{
  "id":      13,
  "test_id": 13
}

actual output

{
  "id": 13
}

I have reviewed this SO post, but that is the only post I can find where someone is experiencing this issue.

I am Running Ruby 1.9.3 and Rails 4.0.0. Thank you for your time.

Any support, input or recommendations would be very much appreciated.


回答1:


in the attributes list, you should specify test_id as well

attributes :id, :test_id


来源:https://stackoverflow.com/questions/19508144/activemodelserializer-in-rails-serializer-methods-ignored-in-json-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!