Ruby on Rails 5.0.2 - 多个嵌套的Json渲染

时间:2017-05-29 16:58:37

标签: ruby-on-rails json

我在尝试在json中渲染多个嵌套对象时遇到了一些麻烦。

这是我的剧本

def getFullSale
        sale = Sale.find(params[:id])
        render json: sale, include: [:discount_sale, :offer_sale, :mixed_payment, :product_sale => {:include => {:product_history => {include: :product}}}, :refunds => {include: :refund_products}]
end

这适用于:product_sale,但是后面的任何内容都会被忽略。

我需要包括:product_sale和:使用嵌套属性退款。

谢谢!

2 个答案:

答案 0 :(得分:1)

我设法让它发挥作用!

Here

中的积分

解决方案是替换include中的数组并使其像对象一样。

def getFullSale
    sale = Sale.find(params[:id])
    render json: sale, include: {discount_sale: {}, offer_sale: {}, mixed_payment: {}, :product_sale => {:include => {:product_history => {include: :product}}}, :refunds => {include: :refund_products}}
end

我不知道为什么会这样,但现在正在发挥作用! 实际上,改变=> to:不是一个坏主意。

def getFullSale
    sale = Sale.find(params[:id])
    render json: sale, include: {discount_sale: {}, offer_sale: {}, mixed_payment: {}, product_sale: {include: {product_history: {include: :product}}}, refunds: {include: :refund_products}}
end

答案 1 :(得分:0)

也许这是一个愚蠢的观察,但您是否尝试将=>更改为:

json: sale, include: [:discount_sale, :offer_sale, :mixed_payment, :product_sale : {:include : {:product_history : {include: :product}}}, :refunds : {include: :refund_products}]