0

Here are my models:

class OrderItem < ApplicationRecord
   belongs_to :order
   belongs_to :product
end

class Order < ApplicationRecord
   has_many :order_items
end

Here is my controller:

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

I want to also include the product in the order_items. How can I achieve this to get the following JSON:

    {
        "id": 2,
        "order_items": [
            {
                "id": 1,
                "product": {
                    "name": "abc"
                },
            }
        ]
    },
Cœur
  • 37,241
  • 25
  • 195
  • 267
An Nguyen
  • 383
  • 1
  • 3
  • 12

2 Answers2

0

You can reach this with changing include: ['order_items'] to include: ['order_items', 'order_items.product'].

More details you can get here.

nautgrad
  • 414
  • 2
  • 8
0

I have been able to solve this by changing include: ['order_items'] to include: {'order_items': {include: 'product'}}

An Nguyen
  • 383
  • 1
  • 3
  • 12