...

/

Application of the Injection of Relationships

Application of the Injection of Relationships

Learn to incorporate relationships to display the corresponding user information in the JSON output of a product.

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:

Press + to interact
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:

Press + to interact
{
"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 ...