I am trying to set up a relationship in my Rails application similar to the one in the following SO question. Rails Object Relationships and JSON Rendering
I want my JSON to be rendered in the same way as shown which is:
[
{
"modelb": {
"id": "1",
"modela": [insert the ModelA JSON for ID's 1, 2 and 3]
}
{
"modelb": {
"id": "2",
"modela": [insert the ModelA JSON for ID's 3, 4 and 5]
}
}
]
I already have a controller that creates the JSON necessary for Model A, as shown below, but I do not know how to make the ModelB model and controller in order to nest that information into another set of JSON or how to specify which ModelA objects go into which of ModelB's objects.
class JsonsController < ApplicationController
before_action :set_json, only: [:show, :update, :destroy]
# GET /jsons
# GET /jsons.json
def index
@jsons = Json.all
render json: @jsons
end
# GET /jsons/1
# GET /jsons/1.json
def show
render json: @json
end
# POST /jsons
# POST /jsons.json
def create
@json = Json.new(json_params)
if @json.save
render json: @json, status: :created, location: @json
else
render json: @json.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /jsons/1
# PATCH/PUT /jsons/1.json
def update
@json = Json.find(params[:id])
if @json.update(json_params)
head :no_content
else
render json: @json.errors, status: :unprocessable_entity
end
end
# DELETE /jsons/1
# DELETE /jsons/1.json
def destroy
@json.destroy
head :no_content
end
private
def set_json
@json = Json.find(params[:id])
end
def json_params
params.require(:json).permit(:text, :parent, :id)
end
end
Any resources or help would be appreciated.