0

这是我的模型:

class OrderItem < ApplicationRecord
   belongs_to :order
   belongs_to :product
end

class Order < ApplicationRecord
   has_many :order_items
end

这是我的控制器:

def index
    orders = Order.where(nil)
    render json: {'orders': orders}, include: 
    ['order_items'], status: :ok
end

我还想将产品包含在 order_items 中。如何实现这一点以获得以下 JSON:

    {
        "id": 2,
        "order_items": [
            {
                "id": 1,
                "product": {
                    "name": "abc"
                },
            }
        ]
    },
4

2 回答 2

0

include: ['order_items'] 您可以通过更改为 来达到此 目的include: ['order_items', 'order_items.product']

更多详细信息,您可以在此处获取。

于 2018-03-27T08:38:25.590 回答
0

我已经能够通过更改为来解决这个include: ['order_items']问题include: {'order_items': {include: 'product'}}

于 2018-03-27T08:46:26.663 回答