2016-11-26 141 views
0

我有一個名爲featured_products的表只包含兩列(product_id,position)。 在我的GET/featured_products,我想呈現像這樣主動模型串行器,呈現無關鍵的關聯

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

而是我在邏輯上得到這樣的:

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

以下活性型號序列化的文檔,我心中已經嘗試了這些在我featured_product序列化器類:

embed_in_root: true 

belongs_to :product, embed_in_root: true 

但第一個給出錯誤,而第二個更改JSON決不會。

我不知道我是否錯過了我在Active Model Serializer的文檔中找到的答案,或者如果答案是在其他地方找到的,但我沒有設法自己解決這個問題,我會很高興在這裏得到一些建議。

謝謝

回答

0

你也可以試試這個:

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

在這裏,它適合我的具體情況。出於好奇,是否還有將產品「包含」在我的JSON中,同時仍然在FeaturedProductSerializer中序列化它以包含其他東西(比如我的例子中的Position)? – Sonastra

0

好的我發現了一個解決方案,它適用於我的具體情況。

因爲對於每個featured_product,我只想顯示關聯的產品,我最終將其映射到render調用中。

即,我從

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

去的那

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

這樣,產品的串行叫,而不是一個從FeaturedProduct。

0

嘗試

render json: @products, root: false