【问题标题】:Active model serializer, render association without key主动模型序列化器,无键渲染关联
【发布时间】:2016-11-26 14:20:12
【问题描述】:

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

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

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

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

按照 Active Model Serializers 的文档,我在我的 features_product 序列化器类中尝试了这些:

embed_in_root: true

belongs_to :product, embed_in_root: true

但第一个会出错,而第二个不会更改 JSON。

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

谢谢

【问题讨论】:

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


    【解决方案1】:

    你也可以试试这个:

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

    【讨论】:

    • 这里再次适用于我的具体情况。出于好奇,无论如何在我的 JSON 中“包含”该产品,同时仍在 FeaturedProductSerializer 中对其进行序列化以包含其他内容(例如我的位置)?
    【解决方案2】:

    试试

    render json: @products, root: false
    

    【讨论】:

      【解决方案3】:

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

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

      即,我从那个开始

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

      到那个

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

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

      【讨论】:

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