【问题标题】:How do I customize the id of a json-api serialized model with active model serializers?如何使用活动模型序列化程序自定义 json-api 序列化模型的 id?
【发布时间】:2018-02-04 00:08:59
【问题描述】:

我希望能够在活动模型序列化程序中自定义与 json api 适配器一起使用的 id。

也就是说,我有一个项目,其中正在序列化的特定模型的实际 ruby​​-on-rails ID 由于各种原因不被认为是面向公众的,但是可以使用替代的面向公众的唯一标识符。

我想使用此标识符作为 json api 序列化内容的 id,但我无法找出任何明显的方法来覆盖 json api 序列化程序中的 ID。

基本上,给定模型[{ id: 1, alt_id: '2aef7e'}, { id: 2, alt_id: '3b47c0' } ...] 我想要一种创建序列化版本的方法:

{
 "data":
  [{
    "id" : "2aef7e",
    "type" : "my-model",
    "attributes" : {...},
    "relationships" : {...}
   },{
    "id" : "3b47c0",
    "type" : "my-model",
    "attributes" : {...},
    "relationships" : {...}
   }],
 "included" : [ ... ]
}

代替:

{
 "data":
  [{
    "id" : "1",
    "type" : "my-model",
    "attributes" : {...},
    "relationships" : {...}
   },{
    "id" : "2",
    "type" : "my-model",
    "attributes" : {...},
    "relationships" : {...}
   }],
 "included" : [ ... ]
}

但一直无法找到一种明显的方法来覆盖 ID 值以进行序列化。

【问题讨论】:

  • (为什么attribute :id do ... 不起作用?)

标签: ruby-on-rails active-model-serializers json-api


【解决方案1】:

您可以在序列化程序中定义一个方法以避免使用对象的方法。

class MySerializer < ActiveModel::Serializer
  attribute :id
  def id
    object.alt_id
  end
end

【讨论】:

  • 所以我不仔细阅读文档好吗?虽然我仍然很好奇为什么在某些示例中使用块 (attribute(:name) { 'value' }) 对:id 不起作用。
猜你喜欢
  • 1970-01-01
  • 2016-11-21
  • 2014-10-05
  • 2018-09-01
  • 1970-01-01
  • 2015-01-01
  • 2023-04-06
  • 1970-01-01
  • 2019-01-17
相关资源
最近更新 更多