【问题标题】:Use alternate association id for ActiveModel::Serializer association为 ActiveModel::Serializer 关联使用备用关联 ID
【发布时间】:2015-09-11 16:02:57
【问题描述】:

我有一个应用程序,在那里我有正常的 ActiveRecord id 以及一个在外部规范数据库中唯一的唯一字段(例如 ident)。模型如下所示:

class Parent
  has_many :childs, foreign_key: :parent_ident, primary_key: :ident
end

class Child
  belongs_to :parent, foreign_key: :parent_ident, primary_key: :ident
end

出于各种原因,我希望我的 Rails API 的使用者使用规范的 id(例如 ident)而不是应用程序上定义的 id。所以我定义了我的序列化器(使用ActiveModel::Serializer):

class ParentSerializer < ActiveModel::Serializer
  attributes :id, :ident, :other, :stuff
  has_many :children

  def id
    object.ident
  end
end

class ChildSerializer < ActiveModel::Serializer
  attributes :id, ident, :parent_ident, :things

  def id
    object.ident
  end
end

问题是正确生成的 JSON 将我的覆盖 ID 用于顶级属性,但 child_ids 字段中的 ID 是本地 ID,而不是我想要使用的规范 ID。

{
  parents: [
    {
      id: 1234, // overridden correctly in AM::S
      ident: 1234,  
      other: 'other',
      stuff: 'stuff',    
      child_ids: [ 1, 2, 3 ], // unfortunately using local ids
    }
  ],
  childs: [
    {
      id: 2345, // doesn't match child_ids array
      ident: 2345, 
      parent_ident: 1234,
      things: 'things'
    }
  ]
}

问题:有没有办法让父序列化程序使用其关联的ident 字段而不是默认的id 字段?

我尝试将def child_ids 放入ParentSerializer,但没有成功。

我正在使用 Rails 4.2 和 active_model_serializers gem 的 9.3 版本。

【问题讨论】:

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


    【解决方案1】:

    您可以根据docs 为关联指定自定义序列化程序

    has_many :children, serializer: ChildSerializer
    

    【讨论】:

    • 谢谢。我不认为这是问题所在(使用正确的ChildSerializer 而不必指定它),因为问题出在父级渲染它的子级ID(而不是渲染子级本身)。基本上,child_ids: [ id1, id2, id3 ] 应该是child_ids: [ ident1, ident2, ident3 ]
    • 您也可以始终在数据库中执行此操作,然后按原样序列化输出。 SELECT ident AS id ...只是吐出一些想法...你可以在序列化方法中做逻辑,你有调用者的上下文吗?
    猜你喜欢
    • 1970-01-01
    • 2018-10-07
    • 2014-12-05
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多