Reputation: 664
So I have a component for displaying players which uses my displayPlayerObject function. The problem is it is I do not have the correct route for fetching in the function and for POST in my routes.rb. The model relationships have the players belonging to the teams and the route for getting a player is "http://localhost:3000/api/teams/1/players/1" 1 being the team id for the former and player id in the latter. But how do I make the displayPlayerObject work the same way syntax wise? And how should it look like for the POST in routes.rb? Also I suspect my players controller's 'show' is wrong as well.
displayPlayerObject function (edited):
export const displayPlayerObject = (id, teamId, type) => {
return dispatch => {
const data = { id };
fetch(`/api/teams/:team_id/players/show`, {
method: 'post',
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(responseJSON => { dispatch({ type , player_object: responseJSON})
})
}
};
My routes.rb (edited):
Rails.application.routes.draw do
scope '/api' do
post "teams/show", to: 'teams#show'
post "teams/:team_id/players/show", to: 'players#show'
resources :teams do
resources :players
resources :star_players
end
end
end
Players Controller Show (edited):
def show
Player.find(params[:id])
render json: @player, status: 200
end
Upvotes: 1
Views: 92
Reputation: 1920
Let's make it look better.
First of all Player.find_by(id: params[:id])
is nonsense, since find_by(id: params[:id])
is equal to where(id: params[:id]).take
. Better to replace it with classic find(params[:id])
which looks much better.
What about your main question, what is the point to give name for POST
with displayObject
. For me display something means GET it to me. If you want to get some player you need to call api/teams/:team_id/players/:id
. But if you want to create new player you need to make POST request to /api/teams/:team_id/players
route.
P.S.1 Just change request method from POST
to GET
. And then add to your promise this:
.then(res => {
console.log(res)
})
And observe what server returns
P.S.2 Change request to
fetch(`/api/teams/:team_id/players/:id`)
And in controller find player by :id
Upvotes: 1