Rails中的ActiveModel :: Serializer-JSON结果中忽略的序列化器方法 [英] ActiveModel::Serializer in Rails - serializer methods ignored in JSON result

查看:62
本文介绍了Rails中的ActiveModel :: Serializer-JSON结果中忽略的序列化器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 active_model_serializers 为我的Rails模型创建JSON.

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

序列化器

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

  attributes :id

  def test_id
    object.id
  end
end

但是,to_json选项似乎忽略了OptionSerializer中添加的方法:

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

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

预期输出

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

实际输出

{
  "id": 13
}

我已查看此SO帖子,但这是我唯一能找到有人遇到此问题的地方.

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

我正在运行Ruby 1.9.3和Rails 4.0.0.谢谢您的宝贵时间.

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.

推荐答案

在属性列表中,您还应该指定test_id

in the attributes list, you should specify test_id as well

attributes :id, :test_id

这篇关于Rails中的ActiveModel :: Serializer-JSON结果中忽略的序列化器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆