如何制作 link 来更改 Rails 中的变量
How to make a link that changes a variable in Rails
我正在浏览 Odin 项目和 Rails.org 上的 Ruby 指南,但仍然无法弄清楚如何制作 link 将布尔值从 true 更新为错误的。我真的要疯了。
我想制作一个网页,每个人都以自己的名字命名,并为每个人分配游戏中的角色(例如 Innocent/Traitor 游戏中的角色,如《一夜狼人》/《间谍坠落》/《恐怖分子镇的麻烦》)。每个玩家都有一个名为 alive 的布尔值,用于存储他们是否仍在游戏中。
我仍在测试和学习东西,所以现在我只想添加一个 link,当您单击它时,它会将玩家的存活状态从 true 更改为 false。比我在网上任何地方都能找到的人询问的任何事情都要简单。这是我的回购协议:
https://github.com/esimunds/nerf_app
我只有一个玩家模型、玩家控制器和玩家相关视图。有问题的 link 是 index.html.erb 视图中的最后一个 link。
<p id="notice"><%= notice %></p>
<h1>Players</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Alive</th>
<th>Wins</th>
<th>Losses</th>
<th colspan="4"></th>
</tr>
</thead>
<tbody>
<% @players.each do |player| %>
<tr>
<td><%= player.name %></td>
<td><%= player.alive %></td>
<td><%= player.wins %></td>
<td><%= player.losses %></td>
<td><%= link_to 'View', player %></td>
<td><%= link_to 'Edit', edit_player_path(player) %></td>
<td><%= link_to 'Delete', player, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<td><%= link_to 'I/ve been shot', player, method: :put%></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Player', new_player_path %>
我只是想让“我中弹了”link 将相应玩家的存活变量更改为 false,然后让索引视图刷新以显示新的存活状态。我不知道如何或在何处添加影响数据库中任何数据的任何类型的方法。教程只提到创建和删除整个对象,他们教授的唯一编辑是通过我目前用来添加或编辑玩家名称的表格。我觉得这是一个如此基本的问题,但我迷路了。
添加新路线
patch 'shot' => 'players#shot', as: :player_shot
然后一个新的控制器动作
def shot
@player = Player.find(params[:id])
@player.update(shot: true)
end
然后在视图中
button_to 'Shot', player_shot_path(id: player.id), method: :patch, remote: true
我正在浏览 Odin 项目和 Rails.org 上的 Ruby 指南,但仍然无法弄清楚如何制作 link 将布尔值从 true 更新为错误的。我真的要疯了。
我想制作一个网页,每个人都以自己的名字命名,并为每个人分配游戏中的角色(例如 Innocent/Traitor 游戏中的角色,如《一夜狼人》/《间谍坠落》/《恐怖分子镇的麻烦》)。每个玩家都有一个名为 alive 的布尔值,用于存储他们是否仍在游戏中。
我仍在测试和学习东西,所以现在我只想添加一个 link,当您单击它时,它会将玩家的存活状态从 true 更改为 false。比我在网上任何地方都能找到的人询问的任何事情都要简单。这是我的回购协议: https://github.com/esimunds/nerf_app
我只有一个玩家模型、玩家控制器和玩家相关视图。有问题的 link 是 index.html.erb 视图中的最后一个 link。
<p id="notice"><%= notice %></p>
<h1>Players</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Alive</th>
<th>Wins</th>
<th>Losses</th>
<th colspan="4"></th>
</tr>
</thead>
<tbody>
<% @players.each do |player| %>
<tr>
<td><%= player.name %></td>
<td><%= player.alive %></td>
<td><%= player.wins %></td>
<td><%= player.losses %></td>
<td><%= link_to 'View', player %></td>
<td><%= link_to 'Edit', edit_player_path(player) %></td>
<td><%= link_to 'Delete', player, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<td><%= link_to 'I/ve been shot', player, method: :put%></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Player', new_player_path %>
我只是想让“我中弹了”link 将相应玩家的存活变量更改为 false,然后让索引视图刷新以显示新的存活状态。我不知道如何或在何处添加影响数据库中任何数据的任何类型的方法。教程只提到创建和删除整个对象,他们教授的唯一编辑是通过我目前用来添加或编辑玩家名称的表格。我觉得这是一个如此基本的问题,但我迷路了。
添加新路线
patch 'shot' => 'players#shot', as: :player_shot
然后一个新的控制器动作
def shot
@player = Player.find(params[:id])
@player.update(shot: true)
end
然后在视图中
button_to 'Shot', player_shot_path(id: player.id), method: :patch, remote: true