Search⌘ K
AI Features

Application of the Injection of Relationships

Explore how to include associated user objects within product JSON output by modifying serializers and controllers. Learn to update tests to verify nested data and run Rails tests to ensure the API correctly represents relationships in its responses.

In this lesson, we will incorporate the user object into the product.

Add relationship in the serializer

We will start by including the Product model’s relationship with the User model in the serializer:

Ruby
class ProductSerializer
include JSONAPI::Serializer
attributes :title, :price, :published
belongs_to :user
end

This addition will add a relationship key containing the user’s identifier and our JSON will look like this:

Javascript (babel-node)
{
"data": {
"id": "1",
"type": "product",
"attributes": {
"title": "Durable Marble Lamp",
"price": "11.55",
"published": true
},
"relationships": {
"user": {
"data": { "id": "1", "type": "user" }
}
}
}
}

Include user in product_controller.rb

Let’s work out how to include the attributes of the user who owns the product. To do ...