【问题标题】:ActiveModel::Serializer in Rails - serializer methods ignored in JSON resultRails 中的 ActiveModel::Serializer - JSON 结果中忽略的序列化方法
【发布时间】:2013-10-30 17:59:02
【问题描述】:

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

序列化器

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

  attributes :id

  def test_id
    object.id
  end
end

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

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

预期输出

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

实际输出

{
  "id": 13
}

我已经查看了this SO post,但这是我能找到的唯一一篇遇到此问题的帖子。

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

非常感谢任何支持、意见或建议。

【问题讨论】:

    标签: ruby-on-rails json serialization ruby-on-rails-4 active-model-serializers


    【解决方案1】:

    在属性列表中,你也应该指定 test_id

    attributes :id, :test_id
    

    【讨论】:

    • 一直在我面前,我没有注意到。谢谢!
    猜你喜欢
    • 2018-02-01
    • 2014-10-17
    • 2017-10-28
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多