我正在使用Ruby,我正在尝试创建一个API以通过单个POST请求更新所有播放器。我必须更新在请求中具有“ id”的所有玩家。发布请求以Array [JSON]形式给出,因此我必须将每个JSON的所有ID与数据库中的播放器进行比较,并且必须更新具有指定ID的那些ID。这里是发布请求的代码:
{
"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"
}
]
}
这里有代码和参数:
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
但是它不起作用!我什么都没找到。有人可以帮我吗?预先非常感谢!
p = Player.find_by(id: params[:id])
->从您发布的内容来看,没有id
参数,如果存在,则每次循环时都将引用相同的参数。我认为您想要的是p = Player.find_by(id: player['player_id'])
[还要记住,Player.find_by(id: some_value)
正在查看数据库ID,我想它可能与player_id
不同。如果是这种情况,那么player_id
可能应该是玩家表中的其他列,而您应该执行.find_by(player_id: player['player_id'])
此外,如果您只是要更新记录,则应使用update!