I am working with data structured in a tree/hierarchical model for climbing areas, where they are connected through parent and child relationships.
By utilizing the JSON API adapter along with my Active Model Serializer,
class AreaSerializer < ActiveModel::Serializer
attributes :id, :name, :description, :location, :slug
belongs_to :user
belongs_to :parent
has_many :children
end
I am able to fetch an Area with its parent and children included by specifying it in my controller:
class AreasController < ApplicationController
...
def show
area = Area.friendly.find(params[:id])
render json: area, include: [:children, :parent]
end
This results in the expected JSON response containing Area data, along with user_id/type, parent_id/type, children_id/type information within the relationships object. This response is then sent to a mutation in a Vuex store for a Vue SPA.
The issue arises when all related data is jumbled under the 'included' property of the response. I specifically need easy access to the 'parent "slug"' and require a separate array for 'children'.
Although the response does contain both children and parent data, they are all classified as 'type: "areas"', grouped together in a single array. I am seeking a practical method to parse this data in JavaScript so that I can compare the 'parent: data { id: "5" }' from the relationships section to the 'id' of one of the 'included' array elements.
I acknowledge that simplifying this process would involve abandoning the JSON API standard and opting for the default serializer, which directly provides 'parent' and 'children' attributes in the response data.
Is there a way to organize these related objects in JavaScript into distinct arrays or objects? Perhaps it would be beneficial to deviate from the JSON API specification in this case and have more control over the server's data output?
I hope this explanation is clear; I believe others may have encountered a similar challenge, although I couldn't locate any examples...