gpt4 book ai didi

ruby-on-rails - 有源模型序列化程序 : exclude attributes when rendering as a relationship

转载 作者:行者123 更新时间:2023-12-04 07:37:25 25 4
gpt4 key购买 nike

TL; 博士

使用:gem 'active_model_serializers', '~> 0.10.7'
当作为关系包含时,有没有办法从序列化程序中包含/排除选项?像这样的东西:

has_many :options, only: [:id, :name]

?

细节

我有一个序列化程序:
class ProductSerializer < BaseSerializer
attribute :id, :name

has_many :options
end
Option有自己的序列化程序,其中包括其他几个属性
class OptionSerializer < BaseSerializer
attribute :id, :name, :created_at, :updated_at
end

但是,当在 Product 中呈现时关系,我从序列化程序中获得所有选项。但是当列为关系的一部分(而不是单独列出)时,我只想要 idname显示。像这样:
{
"products": [{
"id": "704c5a2d-ef53-4cae-9d3f-132dc18c148a",
"name": "foo",
"options": [{
"id": "704c5a2d-ef53-4cae-9d3f-132dc18c148a",
"name": "bar"
}]
...
}

如果我覆盖关系,我可以到达那里:
def options
object.options.select(:id, :name)
end

...但是 1)这感觉很草率,2)这会产生 N+1 个问题。我也可以创建一个 NestedOptionSerializer然后用它来渲染,但这似乎有点矫枉过正。

当序列化程序作为关系包含时,是否有更简单/更清晰的包含/排除属性的方法?像这样的东西?
has_many :options, only: [:id, :name]

?

最佳答案

您可以尝试创建第二个初始化程序,例如 ProductOption您将在其中定义您希望该关系允许 Product 的属性。序列化程序通过,在这种情况下 attributes :id, :name

class ProductOptionSerializer < ActiveModel::Serializer
attribute :id, :name
end

然后,回到 ProductSerializer ,在关系上指定这个新的序列化程序:
class ProductSerializer < ActiveModel::Serializer
attribute :id, :name

has_many :options, serializer: ProductOptionSerializer
end

关于ruby-on-rails - 有源模型序列化程序 : exclude attributes when rendering as a relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50454626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com