Search code examples
activerecordactive-model-serializersruby-on-rails-5.2

Get a belongs_to relationship from class Ruby on Rails


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"
                },
            }
        ]
    },

Solution

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