【发布时间】: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