【问题标题】:Active Model Serializers: exclude attributes when rendering as a relationship活动模型序列化器:在呈现为关系时排除属性
【发布时间】:2018-05-21 18:26:22
【问题描述】:

TL;DR

使用: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]

?

【问题讨论】:

  • 你找到答案了吗?
  • 问得好,你有没有得到更多关于它的信息?

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


【解决方案1】:

您可以尝试制作第二个初始化程序,例如 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多