mardi 19 avril 2022

How can I render multiple resources in one API request?

This is what I am trying to achieve

"Add a RESTful, read-only API to allow consumers to retrieve Questions with Answers as JSON (no need to retrieve Answers on their own). The response should include Answers inside their Question as well as include the id and name of the Question and Answer users."

So far I have my controllers set up as follows:

class Api::V1::UsersController < ApplicationController

def index
    @users = User.all 
    render json: @users 
end

def show
    @user = User.find(params[:id])
    render json: @user 
end

end

class Api::V1::QuestionsController < ApplicationController

def index
    @questions = Question.where(share: true) 
    render json: @questions
end

end

class Api::V1::AnswersController < ApplicationController

def index
    @answers = Answer.all 
    render json: @answers 
end

end

And my routes are set up like this however I'm sure this is not correct for what I want to achieve

Rails.application.routes.draw do

namespace :api do namespace :v1 do resources :questions do resources :answers do resources :users end end end end

root 'welcome#index'

get 'welcome/index' end

Any help would be appreciated

Aucun commentaire:

Enregistrer un commentaire