活动模型序列化器,无需密钥即可呈现关联

Active model serializer, render association without key

我有一个名为 featured_products 的 table,它只包含两列(product_id,位置)。 在我的 GET /featured_products 上,我想渲染这样的东西

[
   { "name":"Product 1" }
   { "name":"product 2" }
]

但是相反,我从逻辑上得到了这个:

[
   "product":{ "name":"Product 1" }
   "product":{ "name":"product 2" }
]

根据 Active Model Serializers 的文档,我在我的 featured_product 序列化程序中尝试了这些 class:

embed_in_root: true

belongs_to :product, embed_in_root: true

但是第一个给出了错误,而第二个却没有改变 JSON。

我不知道我是否错过了我在 Active Model Serializer 的文档中寻找的答案,或者是否可以在其他地方找到答案,但我没有设法自己解决这个问题,我'很高兴在这里得到一些建议。

谢谢

好的,我找到了适合我的具体情况的解决方案。

因为对于每个 featured_product,我只想显示关联的产品,我最终在渲染调用中映射了它。

即,我从那个开始

render json: FeaturedProduct.all.order(:position)

到那个

render json: FeaturedProduct.all.order(:position).map(&:product)

这样,就会调用 Product 的序列化程序,而不是 FeaturedProduct 中的序列化程序。

你也可以试试这个:

render json: FeaturedProduct.includes(:product).order(:position).map(&:product) # include :product to avoid N + 1 queries on products

尝试

render json: @products, root: false