Reputation: 27
I'm leraning Ruby and I'm trying to create an API to update all the players with a single POST request. I have to update all the players which have the "ids" on the request. The post request is given in Array[JSON] form, so I have to compare all the ids for every JSON with the players in the database and I have to update those who have the id specified. Here the code of the post request:
{
"players": [
{
"player_id": 1,
"shirt_number": "25",
"speed": "47",
"agility": "80",
"shot": "62",
"step": "24",
"technique": "70",
"contrasts": "59",
"resistance": "65",
"parades": "25",
"aggressiveness": "60",
"coldness": "50"
},
{
"player_id": 2,
"shirt_number": "11",
"speed": “52",
"agility": “78",
"shot": “65",
"step": “23",
"technique": “60",
"contrasts": “19",
"resistance": “44",
"parades": "25",
"aggressiveness": "60",
"coldness": "50"
}
]
}
Here there is the code and the parameters:
desc 'Update a team'
params do
requires :players, type: Array[JSON] do
requires :id, type: Integer, desc: "Player ID"
requires :shirt_number, type: String, desc: "Shirt Number"
requires :speed, type: String, desc: "Speed"
requires :agility, type: String, desc: "Agility"
requires :shot, type: String, desc: "Shot"
requires :step, type: String, desc: "Step"
requires :technique, type: String, desc: "Technique"
requires :constrasts, type: String, desc: "Constrasts"
requires :resistance, type: String, desc: "Resistance"
requires :parades, type: String, desc: "Parades"
requires :aggressiveness, type: String, desc: "Aggressiveness"
requires :coldness, type: String, desc: "Coldness"
end
end
post 'update_team' do
params[:players].each do |player|
p = Player.find_by(id: params[:id])
p.update(player)
end
end
But it doesn't work! I didn't find anything about that. Someone can help me? Thank you very much in advance!
Upvotes: 0
Views: 100
Reputation: 518
p = Player.find_by(id: params[:id])
-> From what you've posted, there isn't an id
parameter and if there was, that would be referencing the same parameter each time through your loop. I think what you want is p = Player.find_by(id: player['player_id'])
Also keep in mind that Player.find_by(id: some_value)
is looking at the database ID, which I imagine might be different from the player_id
. If this is the case, then player_id
should probably be a different column in your players table and you would instead do .find_by(player_id: player['player_id'])
Additionally, if you are just updating the record in place, you should use update!
Upvotes: 1